How to get city name against google map latitude and longitude using javascript

Hi There,

Before moving ahead please make sure you have a valid Google API key otherwise after few hits to google service it will throw a daily limit exceed exception in your ajax call. You need a Server API Key for this not Browser API Key from Google.

You need to include below references in your HTML code first.

[code] [/code]

JavaScript Code:

[code]function GetLocation() { navigator.geolocation.watchPosition(callback); } function callback(position) { GoogleAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," + position.coords.longitude + "&key=YOUR API KEY HERE"; //Fetching City Name $.getJSON(GoogleAPI, function (json) { if (Wcity == undefined) { Wcity = json.results[0].address_components[3].short_name; alert(Wcity); } }[/code]

Please note that, in most of the cases Google map throws city name on ".address_components[3]" however you can change it to index ".address_components[2]" as well and trick with the results.

Happy Coding :)

Comments

Popular Posts

GREYCstoration Oil Paint plugin for Photoshop

Service Bus Gateway service stuck at Starting

PowerApps SubmitForm not clearing People Picker value

Apple iPhone sending SMS automatically 00447786205094

Download file failed signature verification and may have been tampered with - Workflow Manger 1.0 Refresh (CU2)