我正试图在 Google map 中将我当前的位置居中。这将使具有特定纬度和经度变量的位置居中。
var coords = new google.maps.LatLng(62.39081100, 17.30692700);
但我试图用这个函数获取用户位置:
function grabMyPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(centerMe);
} else {
alert("You don't support this");
}
}
function centerMe(center) {
var me_location = {
lat: position.coords.latitude,
lon: position.coords.longitude
};
}
然后这样做:
var coords = new google.maps.LatLng(me_location.lat, me_location.lon);
但后来我明白了:
Uncaught TypeError: Cannot read property 'lat' of undefined
那是因为我在一个函数中存储和填充这个“me_location”变量。我怎样才能使它成为“全局”以便它可以在我的函数之外使用?
最佳答案
function grabMyPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(centerMe);
} else {
alert("You don't support this");
}
}
function centerMe(position) {
var coords = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
map.setCenter(coords);
// or
map.panTo(coords);
}
假设您的 map
变量是全局的..
关于javascript - 如何居中我当前的位置? (谷歌地图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15886049/