【问题标题】:Why is my reverse geocoding not working and displaying?为什么我的反向地理编码无法正常工作和显示?
【发布时间】:2019-09-23 16:05:55
【问题描述】:

我有一个附近的搜索地图,每次打开这个地图页面,它都会返回当前位置,现在当我通过坐标获取当前位置时,我想将其反向地理编码为地址名称,问题是我修改了我的代码来自这个来源:https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse

<script>
function getPosition() {
  navigator.geolocation.getCurrentPosition(position => {
    currentLatLon = [position.coords.latitude, position.coords.longitude];
    infowindow = new google.maps.InfoWindow();
    map = new google.maps.Map(
      document.getElementById('map'), {
        center: new google.maps.LatLng(...currentLatLon),
        zoom: 20
      });
      var geocoder = new google.maps.Geocoder();       
    service = new google.maps.places.PlacesService(map);
    document.getElementById("curr").innerHTML=currentLatLon;
    document.getElementById("address").value=currentLatLon;
    geocodeLatLng(geocoder,map,infowindow);
  });
}

 function geocodeLatLng(geocoder, map, infowindow) {
        var input = document.getElementById('curr').value;
        var latlngStr = input.split(',');
        var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
        geocoder.geocode({'location': latlng}, function(results, status) {
          if (status === 'OK') {
            if (results[0]) {
              map.setZoom(11);
              var marker = new google.maps.Marker({
                position: latlng,
                map: map
              });
              infowindow.setContent(results[0].formatted_address);
              infowindow.open(map, marker);
            } else {
              window.alert('No results found');
            }
          } else {
            window.alert('Geocoder failed due to: ' + status);
          }
        });
      }
    </script>

这应该返回地图中的地名,就像我从上面复制的源代码一样 https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse,我的修改可能有什么问题?运行修改后的代码时,控制台出现错误error in the console

这是我没有 api 密钥的完整代码:https://pastebin.com/BhEqRsq0

【问题讨论】:

  • 如何包含 API? document.getElementById('curr').value; 是否包含字符串(您的代码假定它是逗号分隔的字符串)。请提供一个 minimal reproducible example 来证明您的问题。
  • document.getElementById('curr').value 是一个带逗号的字符串
  • 只有在地理位置功能成功检索到位置之后。
  • 这是什么意思?

标签: javascript google-maps reverse-geocoding


【解决方案1】:

您将 lat/lng 坐标设置为 &lt;p&gt; 元素的 innerHTML,而不是其(不支持的)value,这就是它返回 undefined 的原因:

document.getElementById("curr").innerHTML = currentLatLon;

所以修改这段代码:

var input = document.getElementById('curr').value;

到以下:

var input = document.getElementById('curr').innerHTML;

我刚刚运行了您的网络应用程序,并且在上述修复后反向地理编码工作正常。所以希望这会有所帮助!

【讨论】:

  • 我收到 ModuleNotFoundError: No module named 'reverse_geocode'。我有一个虚拟环境,我做了 pip3 install reverse_geocoder
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
相关资源
最近更新 更多