In this article, we will discuss about getting geo-location of any city. For getting geo-location of any city in the form of longitude and latitude, we use Google API. For this, you have to generate a Google API key which I have already discussed in my last article Getting Geo-Location of Current Location. You can use the single for getting the current location as well as for getting the location of any city. Following is the source code and output.
Source Code (jQuery and HTML):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> http://Scripts/jquery-1.4.1-vsdoc.js http://Scripts/jquery-1.4.1.js http://Scripts/jquery-1.4.1.min.js https://maps.googleapis.com/maps/api/js?key=AIzaSyA-Ohtnmw3oor9WTXF1CwyTE_CgDaUDjoE&sensor=false function initialize() { var address = (document.getElementById('my-address')); var autocomplete = new google.maps.places.Autocomplete(address); autocomplete.setTypes(['geocode']); google.maps.event.addListener(autocomplete, 'place_changed', function () { var place = autocomplete.getPlace(); if (!place.geometry) { return; } var address = ''; if (place.address_components) { address = [ (place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '') ].join(' '); } }); } google.maps.event.addDomListener(window, 'load', initialize); function codeAddress() { geocoder = new google.maps.Geocoder(); var address = document.getElementById("my-address").value; geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { success(results[0].geometry.location.lng(), results[0].geometry.location.lat()) } else { alert("Geocode was not successful for the following reason: " + status); } }); } function success(long, lat) { var myLatlng = new google.maps.LatLng(lat, long); var myOptions = { center: myLatlng, zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker = new google.maps.Marker({ position: myLatlng, title: "lat: " + lat + " long: " + long }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content: "User Address Latitude:" + lat + " Longitude:" + long + "" }); infowindow.open(map, marker); } </head> <body> <div> <div> <input type="text" id="my-address" /> <input id="getCords" type="button" value="Find Location" onclick="javascript:codeAddress()" /> <div id="map_canvas" style="width: 500px; height: 400px"></div> </div> </div> </body> </html>
First Enter the City name and click on Find Location as shown below.
Output:-