我正在使用谷歌地图地理位置,但无法弄清楚如何用一个代表用户当前位置的图标替换它的InfoWindow。
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
答案 0 :(得分:0)
如果目标只是添加标记而不是使用InfoWindow
那么这应该指向正确的方向
var map,pos,marker;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
/* add a custom marker rather than infowindow */
marker=new google.maps.Marker({
position: pos,
icon:'http://www.compciv.org/files/images/randoms/obamaicon.png',
map:map,
title:'Position found',
animation: google.maps.Animation.DROP
});
map.setCenter( pos );
},
function(){ handleLocationError( true, map.getCenter() ); }
);
} else {
handleLocationError( false, map.getCenter() );
}
}
function handleLocationError( browserHasGeolocation, pos) {
/* add different marker for errors */
marker=new google.maps.Marker({
position:pos,
icon:'https://cartoon.aminoapps.com/static/bower/emojify.js/images/emoji/skull.png',
map:map,
title:browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.',
animation: google.maps.Animation.DROP
});
return marker;
}