简体   繁体   中英

How to get Latitude and Longitude of any City using Google API and a form?

I am currently designing a project where I need to get the latitude and longitude of whatever city a user types in and once it is typed in, I have a button which once clicked is suppose to get the Latitude and Longitude of this city and put it in two textboxes I have set up. I am using the Google Places API and map as well in my project.

Any ideas of how I might accomplish this as I have been attempting to do this for over a week now.

Check out the google geocoding api .

I built a simple example on jsbin.

$("#city").on("change keyup", function() {
  var city = $(this).val()
  $.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address="+encodeURIComponent(city), function(val) {
    if(val.results.length) {
      var location = val.results[0].geometry.location
      $("#lat").val(location.lat)
      $("#lon").val(location.lng)
    }
  })
})

You have a perfect example here

var place = autocomplete.getPlace();
if (place.geometry.viewport) 
  map.fitBounds(place.geometry.viewport);
else 
{
  map.setCenter(place.geometry.location);
  map.setZoom(17);  //Or any zoom level
}

Just look at the documentation

You'll have to adapt it to your need of course.
Just use the latitude and longitude given in place.geometry object returned.

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