我有一个按钮,如果单击该按钮会在地图上显示用户位置。目前很难我收到此错误Uncaught TypeError: Cannot set property 'position' of undefined
这是我的代码:
<div class="col-sm-offset-4 col-sm-4">
<input type="button" value="Show my location on Map" id="mapButton">
<article></article>
</div>
$('#mapButton').click(function() {
$( "#mapcontainer" ).remove();
function success(position){
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '300px';
mapcanvas.style.width = '300px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
alert(coords);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map("mapcontainer",options)[0];
marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
});
为什么会抛出此错误?
答案 0 :(得分:1)
要映射的第一个参数是div元素。而不是传递mapcontainer&#39;,传递
的document.getElementById(&#34; mapcontainer&#34)
var map = new google.maps.Map(document.getElementById("mapcontainer"),options)[0];
var marker = new google.maps.Marker({
'position': coords,
map: map,
title:"You are here!"
});