Idalia
Idalia

Reputation: 193

How to add a Geocoding Service (For MapBox)

I'm working on a map with mapbox, also it has a list of locations per countries, states and cities, and when I am clicking one of them, their location should be shown.

So I´m adding the geocoder L.mapbox.geocoder of mapbox but the coordinates of some places are not precise enough e.g. US or France.

How can I solve this?

I also thought to use google's geocoding service Google Geocoder. How could I do this ?

Example code

I hope you can help me.

Upvotes: 1

Views: 688

Answers (1)

Manuel
Manuel

Reputation: 2542

If you are going to use mapbox, there is no guarantee for accurate data over the whole world, because mapbox streets is based on a volunteered database called OpenStreetMap: "Data for Mapbox Streets comes primarily from OpenStreetMap, with Natural Earth and our own tweaks used for some parts" [source]. So if you have to be more accurate the google Geocoder should be the API of your choice. The pricing depends on the requests per day.

Here is an google Geocoding example:

<!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> 

Upvotes: 0

Related Questions