我是新手,正在练习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"
})
}
});
最佳答案
两个问题:
JavaScript 区分大小写,这一行:
Map = new google.maps.Map
应该是
map = new google.maps.Map
(注意 map 开头的小写m。)
那么,为什么您没有收到“ undefined variable ”错误或其他错误?因为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 ----------------------------^^^
关于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/