2

I'm trying to use the Mapkit js Geocode function, but I'm not sure how to call this function. Here's my code, I'm getting a null from alert(data). https://developer.apple.com/documentation/mapkitjs/mapkit/geocoder/2973884-lookup

var geocoder = new mapkit.Geocoder({
    language: "en-GB",
    getsUserLocation: true
});

geocoder.lookup("450 Serra Mall, Stanford, CA USA", getResult);

function getResult(data) {
    alert(data);
}
Julia
  • 1,207
  • 4
  • 29
  • 47

3 Answers3

4

The first argument of callback is error. If you have no errors is null.

geocoder.lookup('New York', function(err, data) {
    console.log(data);
});
Daniele Dolci
  • 884
  • 1
  • 9
  • 22
1

You're very close to having the information you're looking for. Update your getResult function as follows:

function getResult(){
    // Make the results accessible in your browser's debugging console so you can see everything that was returned
    console.log(arguments)

    // The results are returned in an array. For example, to get the latitude and longitude
    var lat = arguments[1].results[0].coordinate.latitude
    var lng = arguments[1].results[0].coordinate.longitude

    // Show the results in HTML
    var pre = document.createElement('pre');
    pre.innerHTML = "Latitude: " + lat + " / Longitude: " + lng;
    document.body.appendChild(pre)
}

Be aware that the results array may have more than one entry.

MEK
  • 162
  • 1
  • 5
0
 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8">

 <script src="https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js"></script>

  <style>
   #map {
     width:  100%;
     height: 400px;
   }
  </style>
 </head>

  <body>
    <div id="dvResult" style="width: 100%; height: 20px"></div>
    <div id="map"></div>

  <script>
    mapkit.init({
     authorizationCallback: done => { 
        done('your token');
     },
     language: "es"
   });       

   var mGeocoder = new mapkit.Geocoder({ language: "en-GB", 
                                     getsUserLocation: true });

   mGeocoder.lookup("1000 Coit Rd, Plano TX 75050", (err, data) => {

  if(err)
    alert(err);
  else
  {
    console.log(data);  

    var lat = data.results[0].coordinate.latitude;
    var lng = data.results[0].coordinate.longitude;

    var dvResult = document.getElementById('dvResult');
    dvResult.innerHTML = "Lat: " + lat + " / Lng: " + lng;
 }
});
 </script>
 </body>
 </html>
Lexo
  • 412
  • 4
  • 6