[英]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.