[英]Google Map API how to set marker for current location
我正在学习谷歌地图 API 并在尝试将当前坐标添加到数组时遇到了这个问题。 这是我的代码:
var locations = [];
在 initialize() 我有:
function initialize() {
infowindow = new google.maps.InfoWindow();
var myOptions = {
zoom: 10,
mapTypeControl: true,
navigationControl: true,
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
add_location('Place 1', 37.2846372, -123.3270422);
set_current_location();
set_markers(new google.maps.LatLngBounds(), map);
}
第一个标记已设置,而 set_current_location() 似乎不起作用。 下面是代码的其余部分:
// add new location to the locations array
function add_location(description, lastitude, longtitude) {
locations.push([description, lastitude, longtitude]);
}
// Set all the markers in the location arrays and bound/frame the map
function set_markers(bounds, map) {
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
}
// Get current location based on the IP Address
function set_current_location() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
add_location('My location', position.coords.latitude, position.coords.longitude);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
任何人都可以帮助或给我提示吗? 我想将当前位置添加到位置数组,以便我可以跟踪我添加了多少个位置。 非常感谢。
如果您只是将set_markers()
移动到getCurrentPosition()
的success
回调的末尾并且用户拒绝分享他的位置,您将不会获得地图,而只会获得灰色区域。 您的地图没有center
设置,这是必需的属性。 最好将其定义为:
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(37.339386, -121.894955),
mapTypeControl: true,
navigationControl: true,
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
...
此外,您还可以在getCurrentPosition()
的error
回调结束时调用set_markers()
,因此如果用户拒绝共享其位置,您可以显示可用位置:
// Get current location based on the IP Address
function set_current_location() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
/*
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
*/
add_location('My location',
position.coords.latitude,
position.coords.longitude);
set_markers(new google.maps.LatLngBounds(), map);
}, function error(err) {
console.log('error: ' + err.message);
set_markers(new google.maps.LatLngBounds(), map);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
请参阅jsbin 中的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.