首页 > 解决方案 > 从谷歌地图抓取坐标以添加到表单

问题描述

我正在制作一个表单,我希望用户使用谷歌地图中的 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>

标签: javascriptformsapigoogle-mapsmaps

解决方案


由于我们缺少一些信息,因此很难回答您的问题。您的项目中是否使用地理定位 API 导入了 Google 地图?您可以在https://console.cloud.google.com上创建帐户并生成密钥

之后,您需要在页面加载完成后通过在 Javascript 末尾添加以下代码来调用 initMap()。

(function(){
    initMap();
}());

从那里,您现在可以在 initMap 函数中获取坐标的值,并将它们添加到您需要它们调用的任何pos.lat位置pos.lng

infoWindow.setContent(pos.lat+' / '+pos.lng);

https://jsfiddle.net/SohRonery/q69ra78v/6/


推荐阅读