jquery - "Uncaught TypeError: Failed to execute ' getComputedStyle ' on ' 窗口 ': parameter 1 is not of type ' 元素'.Tq ​​@ VM107 :37mF , 当 gmap 添加时

标签 jquery html google-maps

我是新手,正在练习html和jquery。 谁能帮我解决这个错误? 当我尝试动态添加谷歌地图时,出现了类似 Uncaught typeError: failed to execute 'getComputedStyle on 'window': parameter.

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"
            })
       }
    });

最佳答案

两个问题:

  1. JavaScript 区分大小写,这一行:

    Map = new google.maps.Map
    

    应该是

    map = new google.maps.Map
    

    (注意 map 开头的小写m。)

    那么,为什么您没有收到“ undefined variable ”错误或其他错误?因为The Horror of Implicit Globals .考虑使用 strict mode因此您会收到主动通知。

  2. 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 ----------------------------^^^
    

关于jquery - "Uncaught TypeError: Failed to execute ' getComputedStyle ' on ' 窗口 ': parameter 1 is not of type ' 元素'.Tq ​​@ VM107 :37mF , 当 gmap 添加时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31472616/

相关文章:

php - jquery监听数据库变化

javascript - 如何从 jquery.tablesorter.js 中的列过滤器下拉列表中获取所选选项

javascript - 谷歌地图在 IE7 中不工作

google-maps - 如何通过叠加层检测谷歌地图上的点击事件?

javascript - 添加标记到谷歌地球

jquery - 使用其属性获取元素?

javascript - Jquery添加到下拉列表

javascript - jQuery DataTables TableTools Export - 获取复选框或单选项的值

html - 在 word html 中保留自定义的文字样式

jquery - 如何打印包含很多列的 html 表