简体   繁体   中英

How to get current location (latitude and longitude) and send it to an reverse geocoding API?

I am trying to get my current latitude and longitude and passing it to a web API called OpenCage Geocoder API. This is what I have done:

// reverse geocoding
function geocode() {

let lat,long;
window.onload = function() {
      var startPos;
      var geoSuccess = function(position) {
            startPos = position;
             lat = startPos.coords.latitude;
             long = startPos.coords.longitude;
      };
      navigator.geolocation.getCurrentPosition(geoSuccess);
  };


geoResponse = function(reponse)
{
   document.getElementById("address").innerHTML = response.results[17].toString();
};



let script = document.createElement('script');
script.src = "https://api.opencagedata.com/geocode/v1/json?q="+ lat +","+ long +"&key=00f711f73483427c8577e646aa2bf4bf&jsonp=geoResponse";
document.body.appendChild(script);


}

I'm new to coding, and I am a bit stuck. Is there any easier method to call this particular API, I'm pretty lost. Any help would be great thanks!

I have modified and attached the snippet of your code for Reference! In your getResponse you received the param as reponse and in code you have called the response.results[17].toString() Which got undefined!

  window.onload = function() { navigator.geolocation.getCurrentPosition(function (position) { var lat = position.coords.latitude; var long = position.coords.longitude; var script = document.createElement('script'); script.src = "https://api.opencagedata.com/geocode/v1/json?q="+ lat +","+ long +"&key=00f711f73483427c8577e646aa2bf4bf&jsonp=geoResponse"; document.body.appendChild(script); }); } geoResponse = function(reponse){ document.getElementById("address").innerHTML = reponse.results[0].formatted; } 
  <div id="address"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM