微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery – “未捕获的TypeError:无法在’Window’上执行’getComputedStyle’:参数1的类型不是’Element’.Tq ​​@ VM107:37mF,当gmap添加时

我是新手,练习 HTMLjquery.
有人可以帮我解决这个错误吗?
当我试图动态添加谷歌地图时,我收到一个错误,如未捕获的类型错误:未能在’window’:参数上执行’getComputedStyle’.

html标记是:

<type="submit" id="locate">Find me</button>
<div id="gmap"> </div>

enter code here

    $(document).ready(function () {

        $('#locate').on('click',function (e) {
            e.preventDefault();
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
            }
            else {
                console.log('Geolocation is not supported by your browser');
            }
        });
        var latlng,mapOptions,map;

        showPosition = function (position) {
            latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude)
            mapOptions = {
                center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP,zoom: 15
            }
            Map = new google.maps.Map($('#gmap'),mapOptions);
            var marker = new google.maps.Marker({
                position: latlng,map: map,title: "You are here"
            })
       }
    });

解决方法

两个问题:

> JavaScript区分大小写,这一行:

Map = new google.maps.Map

应该

map = new google.maps.Map

(注意开头的地图中的小写m.)

那么为什么你没有得到“未定义的变量”错误或什么?因为The Horror of Implicit Globals.请考虑使用strict mode,以便您获得主动通知.
> google.maps.Map构造函数希望你给它一个元素作为它的第一个参数,但你不是这样做的.你给它一个jQuery对象:

map = new google.maps.Map($('#gmap'),mapOptions);
//                        ^^^^^^^^^^--- this is a jQuery object

获取jQuery对象中的唯一元素,请使用[0]:

map = new google.maps.Map($('#gmap')[0],mapOptions);
// Here ----------------------------^^^

原文地址:https://www.jb51.cc/jquery/176766.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐