I want to get latitude and longitude of a city by providing the API with the city name. It should work for most cities regardless how the user inputs the city.
For example:
City can be 'miami, US' or city can be 'miami, united states'
How do I print its latitude?
You can use https://ip-api.io/ to get city Name. It supports IPv6.
You can find the code jsfiddled here : http://jsfiddle.net/YphZw/ or below :
$("#btn").click(function(){ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': 'miami, us'}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng()); } else { alert("Something got wrong " + status); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> </head> <body> <input id="btn" type="button" value="search for miami coordinates" /> </body> </html>
If you want more examples for the Javascript API, try this link : https://developers.google.com/maps/documentation/javascript/examples/
The code I wrote is inspired from the geocoding-simple sample.
Regards.
EDIT 1:
You can achieve it using an non-official PHP library. Check this example : http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php (The code is at the bottom=
You can use Google's geocoding service, e.g.,
http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false
That gives you back georeferenced data in a variety of formats (JSON, XML, etc). In any event, the location is definitely in the returned data block.
The API docs are at:
https://developers.google.com/maps/documentation/geocoding/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With