How to obtain longitude and latitude for a street address programmatically (and legally)

Web ServicesApiGeolocationGeocodingStreet Address

Web Services Problem Overview


Supposedly, it is possible to get this from Google Maps or some such service. (US addresses only is not good enough.)

Web Services Solutions


Solution 1 - Web Services

The term you're looking for is geocoding and yes Google does provide this service.

Solution 2 - Web Services

In addition to the aforementioned Google geocoding web service, there is also a competing service provided by Yahoo. In a recent project where geocoding is done with user interaction, I included support for both. The reason is I have found that, especially outside the U.S., their handling of more obscure locations varies widely. Sometimes Google will have the best answer, sometimes Yahoo.

One gotcha to be aware of: if Google really thinks they don't know where your place is, they will return a 602 error indicating failure. Yahoo, on the other hand, if it can peel out a city/province/state/etc out of your bad address, will return the location of the center of that town. So you do have to pay attention to the results you get to see if they are really what you want. There are ancillary fields in some results that tell you about this: Yahoo calls this field "precision" and Google calls it "accuracy".

Solution 3 - Web Services

If you want to do this without relying on a service, then you download the TIGER Shapefiles from the US Census.

You look up the street you're interested in, which will have several segments. Each segment will have a start address and end address, and you interpolate along the segment to find where on the segment your house number lies.

This will provide you with a lon/lat pair.

Keep in mind, however, that online services employ a great deal of address checking and correction, which you'd have to duplicate as well to get good results.

Also note that as nice as free data is, it's not perfect - the latest streets aren't in there (they might be in the data Google uses), and the streets may be off their real location by some amount due to survey inaccuracies. But for 98% of geocoding needs it works perfectly, is free, and you control everything so you're reducing dependencies in your app.

Openstreetmaps has the aim of mapping everything in the world, though they aren't quite there it's worth keeping tabs on as they provide their data under a CC license

However, many (most?) other countries are only mapped by gov't or services for which you need to pay a fee. If you don't need to geocode very much data, then using Google, Yahoo, or some of the other free worldwide mapping services may be enough.

If you have to geocode a lot of data, then you will be best served by leasing map data from a major provider, such as teleatlas.

-Adam

Solution 4 - Web Services

You could also try the OpenStreetMap NameFinder, which contains open source, wiki-like street data for (potentially) the entire world. NameFinder will cease to exist at the end of august, but Nominatim is its replacement.

Solution 5 - Web Services

Google requires you to show a Google map with their data, with a max of 2.5k (was 25k) HTTP requests per day. Useful but you have to watch usage.

They do have

[http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders][1]

(Google has since removed this. If you see a duplicate or cache, I'll link to that.)

...in which I found [GeoNames][2] which has both a downloadable db, free web service and a commercial web service.

[1]: http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders "link to other services" [2]: http://www.geonames.org/

Solution 6 - Web Services

Google's terms of service will let you use their geocoding API for free if your website is in turn free for consumers to use. If not you will have to get a license for the Enterprise Maps.

Solution 7 - Web Services

For use with Drupal and PHP (and easily modified):

function get_lat_long($address) {
  $res = drupal_http_request('http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false');
  return json_decode($res->data)->results[0]->geometry->location;
}

Solution 8 - Web Services

You can have a look at the Google Maps API docs here to get a start on this:

http://code.google.com/apis/maps/documentation/services.html#Geocoding

It also seems to be something that you can do for international addresses using Live Maps also:

http://virtualearth.spaces.live.com/blog/cns!2BBC66E99FDCDB98!1588.entry

Solution 9 - Web Services

You can also do this with Microsoft's MapPoint Web Services.

Here's a blog post that explains how: http://www.codestrider.com/BlogRead.aspx?b=b5e8e275-cd18-4c24-b321-0da26e01bec5

Solution 10 - Web Services

R Code to get the latitude and longitude of a street address

# CODE TO GET THE LATITUDE AND LONGITUDE OF A STREET ADDRESS WITH GOOGLE API
addr <- '6th Main Rd, New Thippasandra, Bengaluru, Karnataka'  # set your address here
url = paste('http://maps.google.com/maps/api/geocode/xml?address=', addr,'&sensor=false',sep='')  # construct the URL
doc = xmlTreeParse(url) 
root = xmlRoot(doc) 
lat = xmlValue(root[['result']][['geometry']][['location']][['lat']]) 
long = xmlValue(root[['result']][['geometry']][['location']][['lng']]) 
lat
[1] "12.9725020"
long
[1] "77.6510688"

Solution 11 - Web Services

If you want to do this in Python:

import json, urllib, urllib2

address = "Your address, New York, NY"

encodedAddress = urllib.quote_plus(address)
data = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddress + '&sensor=false').read()
location = json.loads(data)['results'][0]['geometry']['location']
lat = location['lat']
lng = location['lng']
print lat, lng

Note that Google does seem to throttle requests if it sees more than a certain amount, so you do want to use an API key in your HTTP request.

Solution 12 - Web Services

I had a batch of 100,000 records to be geocode and ran into Google API's limit (and since it was for an internal enterprise app, we had to upgrade to their premium service which is $10K plus)

So, I used this instead: http://geoservices.tamu.edu/Services/Geocode/BatchProcess/ -- they also have an API. (the total cost was around ~200$)

Solution 13 - Web Services

You can try this in JavaScript for city like kohat

var geocoder = new google.maps.Geocoder();
var address = "kohat";
geocoder.geocode( { 'address': address}, function(results, status) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
alert(latitude+" and "+longitude);
  } 
});

enter image description here

Solution 14 - Web Services

In python using geopy PyPI used to get the lattitude,langitude,zipcode etc.. Here is the working sample code..

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="your-app-id")

location = geolocator.geocode("Your required address ")

if location:
    print('\n Nominatim ADDRESS :',location.address)
    print('\n Nominatim LATLANG :',(location.latitude, location.longitude))
    print('\n Nominatim FULL RESPONSE :',location.raw)
else:
   print('Cannot Find')

In Nominatim - Some addresses can't working, so i just tried MapQuest.
It returns correctly. Mapquest provides free-plan 15000 transactions/month. It is enough for me.

Sample code:

import geocoder
g = geocoder.mapquest("Your required address ",key='your-api-key')

for result in g:
   # print(result.address, result.latlng)
   print('\n mapquest ADDRESS :',result.address,result.city,result.state,result.country)
   print('\n mapquest LATLANG :', result.latlng)
   print('\n mapquest FULL RESPONSE :',result.raw)

Hope it helps.

Solution 15 - Web Services

I know this is old question but google changing way to get latitude and longitude on regular based.

HTML code

<form>
	<input type="text" name="address" id="address" style="width:100%;">
	<input type="button" onclick="return getLatLong()" value="Get Lat Long" />
</form>
<div id="latlong">
	<p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p>
	<p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p>
</div>

JavaScript Code

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>

	<script>
	function getLatLong()
	{
		var address = document.getElementById("address").value;
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode( { 'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var latitude = results[0].geometry.location.lat();
				document.getElementById("latbox").value=latitude;
				var longitude = results[0].geometry.location.lng();
				document.getElementById("lngbox").value=longitude;
			} 
		});
	}
	</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOla Eld&#248;yView Question on Stackoverflow
Solution 1 - Web ServicesSijinView Answer on Stackoverflow
Solution 2 - Web ServicesTim FarleyView Answer on Stackoverflow
Solution 3 - Web ServicesAdam DavisView Answer on Stackoverflow
Solution 4 - Web ServicespeSHIrView Answer on Stackoverflow
Solution 5 - Web ServicesRichard WatsonView Answer on Stackoverflow
Solution 6 - Web ServicesCraig WohlfeilView Answer on Stackoverflow
Solution 7 - Web ServicesNate WildermuthView Answer on Stackoverflow
Solution 8 - Web ServicesCarlView Answer on Stackoverflow
Solution 9 - Web ServicesStephen CurialView Answer on Stackoverflow
Solution 10 - Web ServicesSelvaView Answer on Stackoverflow
Solution 11 - Web ServicesSumanView Answer on Stackoverflow
Solution 12 - Web Servicesparas_doshiView Answer on Stackoverflow
Solution 13 - Web ServicesAdiiiView Answer on Stackoverflow
Solution 14 - Web ServicesParthiban SoundramView Answer on Stackoverflow
Solution 15 - Web ServicesMukesh JakharView Answer on Stackoverflow