如何调用Mapkit js Geocode方法

时间:2018-08-14 00:54:27

标签: javascript mapkit apple-maps geocoder

我正在尝试使用Mapkit js Geocode函数,但是不确定如何调用此函数。这是我的代码,我从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);
}

3 个答案:

答案 0 :(得分:0)

您非常接近要查找的信息。如下更新您的getResult函数:

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)
}

请注意,results数组可能有多个条目。

答案 1 :(得分:0)

回调的第一个参数是错误。如果没有错误,则为null。

geocoder.lookup('New York', function(err, data) {
    console.log(data);
});

答案 2 :(得分: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>