如何添加地理编码服务(适用于MapBox)

时间:2016-10-27 17:12:04

标签: javascript geocoding mapbox mapbox-gl

我正在使用mapbox制作地图,并且每个国家/地区,州和城市都有一个位置列表,当我点击其中一个时,应显示其位置。

所以我添加了mapbox的地理编码器L.mapbox.geocoder但是某些地方的坐标不够精确,例如美国或法国。

我该如何解决这个问题?

我还想过使用谷歌的地理编码服务Google Geocoder。 我怎么能这样做?

Example code

我希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

如果您打算使用mapbox,则无法保证全世界的准确数据,因为mapbox街道基于名为OpenStreetMap的自愿数据库:“Mapbox Streets的数据主要来自OpenStreetMap,使用Natural Earth和我们自己的调整用于某些部分“ [source]。因此,如果您必须更准确,Google Geocoder应该是您选择的API。 pricing取决于每天的请求。

以下是Google地理编码示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Geocoding service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input id="submit" type="button" value="Geocode">
    </div>
    <div id="map"></div>
    <script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {lat: -34.397, lng: 150.644}
  });
  var geocoder = new google.maps.Geocoder();

  document.getElementById('submit').addEventListener('click', function() {
    geocodeAddress(geocoder, map);
  });
}

function geocodeAddress(geocoder, resultsMap) {
  var address = document.getElementById('address').value;
  geocoder.geocode({'address': address}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      resultsMap.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap"
        async defer></script>
  </body>
</html>