javascript - 从谷歌地图抓取坐标以添加到表单
问题描述
我正在制作一个表单,我希望用户使用谷歌地图中的 GPS 位置输入他们当前的位置。我已经阅读了 Google Maps API 文档,但我仍然对如何集成它有点迷茫。我会很感激任何帮助,JS 对我来说仍然很新,而且学习起来并不容易。
这是我从 Google Maps API 使用的代码。
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 18.2208, lng: -66.5901},
zoom: 7,
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Localización encontrada.');
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);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAwnKnBH4qxyjHYkg3QlJP46-yG_o4QkSc&callback=initMap">
</script>
解决方案
由于我们缺少一些信息,因此很难回答您的问题。您的项目中是否使用地理定位 API 导入了 Google 地图?您可以在https://console.cloud.google.com上创建帐户并生成密钥
之后,您需要在页面加载完成后通过在 Javascript 末尾添加以下代码来调用 initMap()。
(function(){
initMap();
}());
从那里,您现在可以在 initMap 函数中获取坐标的值,并将它们添加到您需要它们调用的任何pos.lat
位置pos.lng
。
infoWindow.setContent(pos.lat+' / '+pos.lng);
推荐阅读
- ios - 除了 expires_date_ms 之外,我还应该检查 cancel_date_ms 以获取自动续订订阅吗?
- linux - 如果特定用户无法写入目录,则 Linux shell 脚本会检查目录
- rubymine - “查找快捷方式”在 RubyMine 中找不到现有的快捷方式
- python - 索引搜索:以准确性换取绩效
- laravel - 如何在 JS 中正确获取对象长度
- jenkins - 无法在 JenkinsFile 脚本中使用变更集
- vba - 搜索并替换字符串,但搜索字符串和替换字符串都超过了字符限制
- sql-server - 为什么在 sql server 中无法在十进制数据类型转换中返回正确的错误?
- html - Bootstrap 响应式网格列,无需清除
- glassfish - 如何为我的 payara 网络应用程序配置 glassfish-resource.xml 和 web.xml?