Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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

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.

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.

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.

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;
}

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

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

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"

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.

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

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

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.

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>

For more information refer this link https://www.phpkida.com/java-script/get-latitude-longitude-from-address/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top