最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get Latitude and Longitude of any City using Google API and a form? - Stack Overflow

programmeradmin2浏览0评论

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 acplish this as I have been attempting to do this for over a week now.

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 acplish this as I have been attempting to do this for over a week now.

Share Improve this question asked Mar 19, 2015 at 14:10 MrWeiserMrWeiser 493 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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./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 = autoplete.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.

发布评论

评论列表(0)

  1. 暂无评论