我正在努力完成两件事 1)拉取用户当前位置 2)然后将其显示在谷歌地图上
根据我的研究,我发现我可以使用以下方法来获取用户的当前位置
navigator.geolocation.getCurrentPosition(success);
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
};
以及以下内容来启动谷歌地图
function initMap() {
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
所以我遇到的问题是如何同时完成这两个任务? 我尝试将第二个函数放入第一个函数中,但这不起作用...... 提前感谢大家的帮助!
最佳答案
initMap 需要知道位置是什么。目前,您正在 initMap 中将位置设置为“uluru”;相反,尝试将坐标传递到函数中,然后从该对象中提取坐标(您可以重用该对象,但必须考虑到这些字段称为经度
/latitude
在第一种情况下,lng
/lat
在第二种情况下)。像这样的事情:
navigator.geolocation.getCurrentPosition(success);
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
initMap(crd);
};
function initMap(coordinates) {
var location = {'lng': coordinates.longitude, 'lat': coordinates.latitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: location
});
var marker = new google.maps.Marker({
position: location,
map: map
});
}
关于javascript - 如何提取用户当前位置并显示在谷歌地图API上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48387573/