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

15

77

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

Ailis answered 1/10, 2008 at 16:22 Comment(0)
P
71

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

Proximate answered 1/10, 2008 at 16:24 Comment(4)
Excellent! The section "Geocoding via HTTP" seems to be what I'm looking for.Quartzite
Just be sure that you keep within the usage rules. I think Google only allows the use of this if you show the locations on a Google Map. It is not allowed to use it for other purposes, but you should check the licence and usage rules.Avid
v2 (deprecated since 2010) is shutting down completely in just a few months (May 2013), so recommend to not build anything new with this one anymore!Darceydarci
Obtaining it through the service is allowed but storing it for later use is not. See the comment (under the answer) about it here https://mcmap.net/q/267569/-country-region-codes-iso-3166-1-iso-3166-2-to-longitude-and-latitudeHerb
C
22

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".

Callis answered 1/10, 2008 at 16:34 Comment(1)
A jsfiddle with an example of the replacement for the Yahoo service, Nokia's ovimaps: jsfiddle.net/MgjGrBelt
P
15

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

Peso answered 1/10, 2008 at 16:31 Comment(2)
This wouldn't work (for this question; in general it sounds fine for the US), as the question already states that a solution that only works for US addresses would not be an acceptable solution.Avid
That's true, but originally the question did not state this - edits made by the author within 15 minutes of the original post are not considered edits. Still, I'll update the answer.Peso
A
9

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.

Avid answered 15/1, 2009 at 9:36 Comment(0)
A
7

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

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

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

Amadou answered 29/9, 2009 at 16:49 Comment(2)
Unfortunately it seems like the groups.google.com link no longer exists... Thank you for the geonames link however, looks promising!Darceydarci
Point of correction/clarification: Google "v3" API allows 2,500 requests per day (per IP address!), not 25k. See developers.google.com/maps/documentation/geocoding/#LimitsDarceydarci
S
5

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.

Solicitous answered 1/10, 2008 at 16:42 Comment(0)
U
3

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;
}
Understudy answered 26/3, 2013 at 19:20 Comment(1)
Super ! , Thank god read all the answer ,thats y i can find your answer. Shall i know is there any restrictions of using this url in normal php . like number of request per day ? @NateGlossographer
C
2

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

Crosspurpose answered 1/10, 2008 at 16:26 Comment(0)
S
2

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

Slimsy answered 4/3, 2009 at 6:51 Comment(1)
Above link seems like brokenLorie
F
2

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"
Falgout answered 13/5, 2015 at 9:15 Comment(0)
S
2

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.

Surroundings answered 21/7, 2015 at 17:36 Comment(0)
P
2

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$)

Ptero answered 18/2, 2016 at 22:16 Comment(0)
T
1

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

Tasse answered 21/11, 2016 at 10:45 Comment(0)
E
1

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.

Eisenberg answered 31/1, 2019 at 10:22 Comment(0)
C
1

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>
Contraception answered 21/2, 2019 at 6:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.