[ACCEPTED]-How to obtain longitude and latitude for a street address programmatically (and legally)-street-address
The term you're looking for is geocoding 2 and yes Google does provide this service.
In addition to the aforementioned Google geocoding web service, there 19 is also a competing service provided by Yahoo. In a recent project 18 where geocoding is done with user interaction, I 17 included support for both. The reason is 16 I have found that, especially outside the 15 U.S., their handling of more obscure locations 14 varies widely. Sometimes Google will have 13 the best answer, sometimes Yahoo.
One gotcha 12 to be aware of: if Google really thinks 11 they don't know where your place is, they 10 will return a 602 error indicating failure. Yahoo, on 9 the other hand, if it can peel out a city/province/state/etc 8 out of your bad address, will return the 7 location of the center of that town. So 6 you do have to pay attention to the results 5 you get to see if they are really what you 4 want. There are ancillary fields in some 3 results that tell you about this: Yahoo 2 calls this field "precision" and 1 Google calls it "accuracy".
If you want to do this without relying on 32 a service, then you download the TIGER Shapefiles from the 31 US Census.
You look up the street you're 30 interested in, which will have several segments. Each 29 segment will have a start address and end 28 address, and you interpolate along the segment 27 to find where on the segment your house 26 number lies.
This will provide you with a 25 lon/lat pair.
Keep in mind, however, that 24 online services employ a great deal of address 23 checking and correction, which you'd have 22 to duplicate as well to get good results.
Also 21 note that as nice as free data is, it's 20 not perfect - the latest streets aren't 19 in there (they might be in the data Google 18 uses), and the streets may be off their 17 real location by some amount due to survey 16 inaccuracies. But for 98% of geocoding 15 needs it works perfectly, is free, and you 14 control everything so you're reducing dependencies 13 in your app.
Openstreetmaps has the aim of 12 mapping everything in the world, though 11 they aren't quite there it's worth keeping 10 tabs on as they provide their data under 9 a CC license
However, many (most?) other 8 countries are only mapped by gov't or services 7 for which you need to pay a fee. If you 6 don't need to geocode very much data, then 5 using Google, Yahoo, or some of the other 4 free worldwide mapping services may be enough.
If 3 you have to geocode a lot of data, then 2 you will be best served by leasing map data 1 from a major provider, such as teleatlas.
-Adam
You could also try the OpenStreetMap NameFinder, which contains 3 open source, wiki-like street data for (potentially) the 2 entire world. NameFinder will cease to exist 1 at the end of august, but Nominatim is its replacement.
Google requires you to show a Google map 7 with their data, with a max of 2.5k (was 6 25k) HTTP requests per day. Useful but you 5 have to watch usage.
They do have
http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders
(Google 4 has since removed this. If you see a duplicate 3 or cache, I'll link to that.)
...in which 2 I found GeoNames which has both a downloadable db, free 1 web service and a commercial web service.
Google's terms of service will let you use 4 their geocoding API for free if your website 3 is in turn free for consumers to use. If 2 not you will have to get a license for the 1 Enterprise Maps.
For use with Drupal and PHP (and easily 1 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 4 docs here to get a start on this:
http://code.google.com/apis/maps/documentation/services.html#Geocoding
It also 3 seems to be something that you can do for 2 international addresses using Live Maps 1 also:
http://virtualearth.spaces.live.com/blog/cns!2BBC66E99FDCDB98!1588.entry
You can also do this with Microsoft's MapPoint 2 Web Services.
Here's a blog post that explains 1 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"
0
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 3 Google does seem to throttle requests if 2 it sees more than a certain amount, so you 1 do want to use an API key in your HTTP request.
I had a batch of 100,000 records to be geocode 6 and ran into Google API's limit (and since 5 it was for an internal enterprise app, we 4 had to upgrade to their premium service 3 which is $10K plus)
So, I used this instead: http://geoservices.tamu.edu/Services/Geocode/BatchProcess/ -- they 2 also have an API. (the total cost was around 1 ~200$)
You can try this in JavaScript for city 1 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);
}
});
In python using geopy PyPI used to get the lattitude,langitude,zipcode 5 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 4 Nominatim - Some addresses can't working, so 3 i just tried MapQuest.
It returns correctly.
Mapquest 2 provides free-plan 15000 transactions/month. It 1 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 2 way to get latitude and longitude on regular 1 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>
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.