I have a textbox in my page which gets a location name and button with text getLat&Long
. Now on clicking my button I have to show an alert of latitude
and longitude
of the location in the textbox. Any suggestion?

- 795
- 9
- 17

- 523
- 1
- 4
- 9
-
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true more info here https://developers.google.com/maps/documentation/geocoding/ – zzart Jul 04 '12 at 13:07
7 Answers
You can use the Google Geocoder service in the Google Maps API to convert from your location name to a latitude and longitude. So you need some code like:
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// do something with the geocoded result
//
// results[0].geometry.location.latitude
// results[0].geometry.location.longitude
}
});
Update
Are you including the v3 javascript API?
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false">
</script>

- 42,006
- 17
- 96
- 122
-
-
The sensor param is no longer used or required. http://stackoverflow.com/questions/8616764/what-is-the-sensor-parameter-in-google-places-api-good-for – RedBlueThing Nov 04 '15 at 23:26
-
11It should be `results[0].geometry.location.lat()` and `results[0].geometry.location.lng()` – Maria Ines Parnisari Aug 31 '16 at 17:22
I hope this can help someone in the future.
You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script type="text/javascript">
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(' ');
}
});
}
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) {
alert("Latitude: "+results[0].geometry.location.lat());
alert("Longitude: "+results[0].geometry.location.lng());
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input type="text" id="my-address">
<button id="getCords" onClick="codeAddress();">getLat&Long</button>
</body>
</html>
Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.
Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).
Hope this helps, and read the documentation for more information, cheers.
Edit #1: Fiddle

- 1,507
- 2
- 20
- 28
-
1yes thanks! the lat() lng() is perfect because seems to change from request to request randomly with actual properties like "k" and "A" or someother weird ones like that for lat lng. You are coool. – King Friday Mar 11 '14 at 21:31
-
-
@Supertecnoboff works without an API key but you won't get the benefits. Check what Google says about the: [API Key](https://developers.google.com/maps/documentation/geocoding/?hl=en#api_key). Also I made a: [Fiddle](http://jsfiddle.net/0b0az4fr/). – Ariel May 22 '15 at 01:15
-
@Ariel I have used your code but in my application using same code getting DENIED but in fiddle it is working fine why? – 3 rules Sep 18 '18 at 07:03
-
@3rules I don't know why it did not work for you. I just tried it locally and had no problem at all, just uploaded a pastebin so you can copy&paste this html: https://pastebin.com/BQSZwm6D. Copy & paste that into a new html and open it, it worked for me. Open a new question in SO exposing the relevant code and give me the link to look into it. Cheers! – Ariel Sep 20 '18 at 13:23
-
@Ariel yes it's working fine in jsfiddle but not in my application...I will test again and come back... – 3 rules Sep 21 '18 at 10:02
http://maps.googleapis.com/maps/api/geocode/OUTPUT?address=YOUR_LOCATION&sensor=true
OUTPUT = json or xml;
for detail information about google map api go through url:
http://code.google.com/apis/maps/documentation/geocoding/index.html
Hope this will help

- 1,780
- 3
- 16
- 33
-
1This is awesome! Just one question, does this require an API key? – Supertecnoboff May 20 '15 at 09:32
The below is the code that i used. It's working perfectly.
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var myLatLng = results[0].geometry.location;
// Add some code to work with myLatLng
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
Hope this will help.

- 91
- 1
- 1
I hope this will be more useful for future scope contain auto complete Google API feature with latitude and longitude
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
Complete View
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete With Latitude & Longitude </title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#pac-input {
background-color: #fff;
padding: 0 11px 0 13px;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
}
#pac-input:focus {
border-color: #4d90fe;
margin-left: -1px;
padding-left: 14px; /* Regular padding-left + 1. */
width: 401px;
}
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
function initialize() {
var address = (document.getElementById('pac-input'));
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(' ');
}
/*********************************************************************/
/* var address contain your autocomplete address *********************/
/* place.geometry.location.lat() && place.geometry.location.lat() ****/
/* will be used for current address latitude and longitude************/
/*********************************************************************/
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('long').innerHTML = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="lat"></div>
<div id="long"></div>
</body>
</html>

- 1,352
- 3
- 13
- 37
I would suggest the following code, you can use this <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
to get the latitude and longitude of a location, although it may not be so accurate however it worked for me;
code snippet below
<!DOCTYPE html>
<html>
<head>
<title>Using Javascript's Geolocation API</title>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
var lat = geoip_latitude();
var long = geoip_longitude();
document.write("Latitude: "+lat+"</br>Longitude: "+long);
</script>
</body>
</html>

- 3,375
- 1
- 25
- 19
Enter the location by Autocomplete and rest of all the fields: latitude and Longititude values get automatically filled.
Replace API KEY with your Google API key
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
</head>
<body>
<textarea placeholder="Enter Area name to populate Latitude and Longitude" name="address" onFocus="initializeAutocomplete()" id="locality" ></textarea><br>
<input type="text" name="city" id="city" placeholder="City" value="" ><br>
<input type="text" name="latitude" id="latitude" placeholder="Latitude" value="" ><br>
<input type="text" name="longitude" id="longitude" placeholder="Longitude" value="" ><br>
<input type="text" name="place_id" id="location_id" placeholder="Location Ids" value="" ><br>
<script type="text/javascript">
function initializeAutocomplete(){
var input = document.getElementById('locality');
// var options = {
// types: ['(regions)'],
// componentRestrictions: {country: "IN"}
// };
var options = {}
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
var placeId = place.place_id;
// to set city name, using the locality param
var componentForm = {
locality: 'short_name',
};
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById("city").value = val;
}
}
document.getElementById("latitude").value = lat;
document.getElementById("longitude").value = lng;
document.getElementById("location_id").value = placeId;
});
}
</script>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?libraries=places&key=API KEY"></script>
<script src="https://fonts.googleapis.com/css?family=Roboto:300,400,500></script>

- 2,756
- 4
- 33
- 57
-
How can I add COUNTRY and ADMINISTRATIVE REGION to this solution? I want country, administrative region (state), city, lat and long. – Marthinus Strydom Jun 06 '20 at 08:07