Can I find out if a coordinate is inside a city? - google-maps-api-3

Let's say I have a LatLng object, is there any way of checking if it represents a possible location within a city? How can I get the limits of a city?
I'm using Google Map V3.

Have you tried reverse geocoding?
http://code.google.com/apis/maps/documentation/javascript/services.html#ReverseGeocoding
You could check the formatted address to see if the city matches what you're looking for. I'm not sure how accurate this will be for your application, but it's an option.
function codeLatLng() {
var geocoder = new google.maps.Geocoder(),
latlng = new google.maps.LatLng(40.730885, -73.997383);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
console.log(results[1]);
console.log(results[1].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}

City limits and other municipalities are constantly re-drawn. There are certain services that exist to help you find them, but I'm not positive that Google keeps a record of city limits inside their data for the Google maps. Here's a discussion in google groups about it. A snippet from that site:
Depending where you are in the world, city limits and other
administrative boundaries are CONSTANTLY being changed, and it's even
sometimes difficult for local governments to keep their data current
because of annexations and other changes. Also, 'city' might be
something relative small or the size of Shanghai. Also, different
countries can also have sometimes conflicting definitions what
administrative unit is the actual definition - a good example is
China. Probably your best approach is to get your data from a local
government or a data supplier and build your own.

You can use Reverse Geocoding in the Google Geocoder API and check the locality entries and perhaps sublocality entries of results returned. http://code.google.com/apis/maps/documentation/geocoding/#Types
Note that this probably won't work so well if you have addresses all over the world and want to know "What city is this LatLng in?" On the other hand, it will probably work reasonably well if you want to know "Is this LatLng within Chicago?" There are areas of the world where the data is fairly complete and sensible, and areas where it is incomplete and/or organized in ways you might not expect. (Apparently, the UK uses "county" and "state" very differently from the USA, for example. Even if I'm wrong about that, you get the idea.)

Related

Quality of result set

I use the here PlacesServices to retrieve information what's around me. Often I get results that are quite ambiguous / duplicate because outdated data appears to be in the result set that reduces the quality quite significantly. How can we feed back changes to the community or how and when does here get updates for those categories, e.g. restaurants or petrol-stations?
Is there a way to dedup?
This is a good example for 3/6 duplicates (same petrol station) since the chain changed some time ago dependent of the direction on the highway.
https://places.ls.hereapi.com/places/v1/places/276u1jne-8c62ebd6159c441eba290df4efdcfd1d;context=Zmxvdy1pZD02ZWQ0YzViNS0wMzgxLTUxZDAtOTg2ZC00NjQ3YTVjNWJhYTJfMTU3NTY2NjU1MTYwM18wXzE1NCZyYW5rPTI
https://places.ls.hereapi.com/places/v1/places/276u1jne-3c240a265c6e48d698a400b7d8738202;context=Zmxvdy1pZD02ZWQ0YzViNS0wMzgxLTUxZDAtOTg2ZC00NjQ3YTVjNWJhYTJfMTU3NTY2NjU1MTYwM18wXzE1NCZyYW5rPTQ
3 chains for a single petrol station
Finally, is there a solution how I'd only obtain those in my travel direction?
var query = {"in": lat +"," + lng +";r="+distance*1000,"cat" : categories +",pretty"};
let entryPoint = H.service.PlacesService.EntryPoint;
await this.places.request(entryPoint.EXPLORE, query,
function(response) {
values = response.results.items;
}, function(resp) {
console.log('ERROR: '+resp);
});
Best regards and many thanks in advance
O.
In general the feedback related to HERE Map data can be reported by either the Map Feedback API , the details on the API are available on the documentation page , or The Online Tool HERE Map Creator could be used.
With respect to retrieving POIs, it is possible to request POIs along the route using the "browse/by-corridor" (documentation) end point where the route shape and a radius could be provided as a corridor. It should be noted however the API does not consider the heading direction of the route and may return POIs on the other side of a road. Example :
https://places.ls.hereapi.com/places/v1/browse/by-corridor?route=[52.5199356,13.3866272|52.5100899,13.2816896|52.4351807,13.1935196|52.4107285,13.1964502|52.38871,13.1557798|52.3727798,13.1491003|52.3737488,13.1154604|52.3875198,13.0872202|52.4029388,13.0706196|52.4105797,13.0755529]&apiKey=API_KEY

How to reliably get county from Google Autocomplete/Details

If I use Google Place Autocomplete for "Alpha Loft Elm" I get an address that includes only level 1 (state) in the administrative areas. But if I autocomplete for the same place using the returned formatted_address, "844 Elm St, Manchester, NH 03101, United States", I get level 2 (county) as well, with a different place-id.
I see the same behavior for other places as well. I see the same behavior from the Place Details API, when I give it the place-id returned in each case.
I need the county, and need to support autocomplete by place name.
The only workaround I've found for this is to use Place Search (textsearch) on the returned formatted_address, then use Place Details on the placeId returned for the address to get the county.
Is there a better approach?
(Also posted as a bug report on gmaps-api-issues.)
So far I am not aware of any other solution then after using Autocomplete to get the accurate address and place_id to use something like the following code to retrieve the "political" structure behind that address.
if (place.place_id) {
var service = new google.maps.places.PlacesService(map);
service.getDetails({placeId: place.place_id}, function (PlaceResult, PlacesServiceStatus) {
console.log(PlaceResult);
});
}

browser position.address.postalCode always null

I noticed that in FF4 i can use geolocalisation object
position.address.postalCode to find the postalCode.
When testing on FF10 I noticed that position.address is always null, while I can still use position.coords without any problem to find longitude or latitude.
Can someone please tell me if there is simple way to find out postalCode in FF10 with position object?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(findClosestAgencies);
}
function findClosestAgencies(position) {
alert("postalCode:" + position.address.postalCode);
alert("latitude:" + position.coords.latitude);
}
my code:
Thank you
According to the spec:
http://dev.w3.org/geo/api/spec-source.html#position_interface
Position is only required to have coordinates and timestamp. FF4 may have had some additional data, but its not guaranteed to be there since its not part of the spec. Try using the coordinates with an address finding service.
The address is only available when it's available; there's no guarantee that it will be non-null, in other words. It depends on how much information the browser can get.
If you can only get the lat/long, you might be able to fall back to using another geolocation web service. (Such a service is almost certainly also not guaranteed to return a postal address; if I'm using your website from a boat on a large lake, for example, I might have no meaningful postal address under any circumstances.)

Correct address format to get the most accurate results from google GeoCoding API

Is there any standard format to supply the address string to Google GeoCoding API to get the most accurate results on map.
For Eg. following query not giving correct result.
http://maps.googleapis.com/maps/api/geocode/xml?address=bloom,Bloomfield,CT,06002,USA&sensor=false
Thanks
Mandeep
I believe the suggested format is:
House Number, Street Direction, Street Name, Street Suffix, City, State, Zip, Country
The results get less specific the less information you can supply, obviously.
In your sample, the geocoder is searching for a street named 'bloom', of which there are similar matches in OH instead of CT. Removing 'bloom' from the query and then searching returns Bloomfield, CT.
Definition of Google address search:
address - The street address that you want to geocode, in the format used by the national postal service of the country concerned. Additional address elements such as business names and unit, suite or floor numbers should be avoided.
https://developers.google.com/maps/documentation/geocoding/#geocoding
How should I format my geocoder queries to maximise the number of successful requests?
The geocoder is designed to map street addresses to geographical coordinates. We therefore recommend that you format geocoder requests in accordance with the following guidelines to maximise the likelihood of a successful query:
Specify addresses in accordance with the format used by the national postal service of the country concerned.
Do not specify additional address elements such as business names, unit numbers, floor numbers, or suite numbers that are not included in the address as defined by the postal service of the country concerned.
Use the street number of a premise in preference to the building name where possible.
Use street number addressing in preference to specifying cross streets where possible.
Do not provide 'hints' such as nearby landmarks.
https://developers.google.com/maps/faq#geocoder_queryformat
I found the answer incomplete and it lacked a source.
Look here: https://developers.google.com/places/documentation/autocomplete#place_autocomplete_responses
The maps autocompletion API from google returns a much simpler format: "Street address, City, Country"
Now you can use a string like that to search for an address and it should lead to one exact result.
In addition if you use the autocompletion API you will get a unique identifier too which can be used for further detail requests.
The format of the street address greatly depends on the location where you actually are.
In the US "House number, street direction, street name, street suffix" might make sense, in most of Europe it will not lead to successful query.
Addresses in most of EU are different (often "Streetname number suffix") like "Kumpelstraat 25A","Psolevcu 331/26b") and I guess we'd be surprised if we look at some eastern countries.
So if you bind your code to a single area (US, most of EU) you might be good hardcoding the format.
If you want to have a more flexible system you either need to find out propper formating for your target audience or query one of googles APIs to automatically get a proper string.
The one I linked is very good but requires an API key with a free request limit per day.
I stumbled upon this question and found a solution that worked for me:
I think the answer can be found by using component filtering, look at:
https://developers.google.com/maps/documentation/geocoding/#ComponentFiltering
An example in Javascript:
var request = require('request');
var url = "https://maps.googleapis.com/maps/api/geocode/json?" +
"address=Herengracht 180" +
"&components=postal_code:1016 BR|country:NL" +
"&sensor=false";
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
else {
console.log('error', error);
}
});
No need to avoid apartment units. This works:
https://maps.googleapis.com/maps/api/geocode/xml?address=14202+N+42nd+St+Unit+301+33613
"Apt", "Room", and "Suite" work as well
They all return 301 as subpremise and are shown in "formatted_address" as "#301."
Paul sends...
I found that official country codes like "US", "DE", "FR" do not work well. Replacing them with the full country name gives much better results for me.
I did not find a source where that is stated.

Geocoding Tweets on a Google Map

Would really appreciate any help with my issue. I've been looking at this terrific tutorial by Marcin Dziewulski who integrated recent tweets and twitter user avatars onto a Google Map. Basically he places the users avatar where they last tweeted. I highly recommend checking the tutorial out here:
http://tympanus.net/codrops/2011/04/13/interactive-google-map/
It all seems to make sense except when it comes down to the actual geocoding of the user. The code works beautifully when the different tweeters are from different cities. However, let's say you wanted to track certain users in one city. They're all geocoded from the center of the city and you can only see one avatar at a time. If you refresh the page, another one will show up, in the exact same spot. This obviously isn't what I want. I assume the problems is in this bit of code:
var users = o.twitter.get(), arr = new Array;
for (i in users){
var user = users[i];
$.getJSON('http://twitter.com/users/show/'+user+'.json?callback=?', function(data) {
var img = data.profile_image_url,
screen_name = data.screen_name;
geocoder.geocode({ address: data.location }, function(response, status){
if (status == google.maps.GeocoderStatus.OK) {
var x = response[0].geometry.location.lat(),
y = response[0].geometry.location.lng();
marker = new google.maps.Marker({
icon: img,
map: map,
title: screen_name,
position: new google.maps.LatLng(x, y)
});
I think something needs to change in the geocoder.geocode({ address: data.location } bit of code, but not 100% positive. I can't seem to find the solution in the Twitter API documentation either.
My question is basically this...can the code above be altered so that it gathers more precise lat and long. coordinates from where tweets are actually generated and then display them correctly at those locations? In other words, don't just put a tweet from NYC in the middle of NYC, but place the avatar at the EXACT location.
I've tested this with my own tweets, with the the location feature of twitter enabled. I just can't figure this out! Thanks again to anyone who can help!
Best,
Brandon
The problem is that the vast majority of tweets are not geocoded but the coords are simply guessed from the user's location settings. If you wanted to display this in an interesting way, consider doing a uniform distribution of "center of city" latlongs. This is what census data map-makers often do when they don't have any more exact positioning data than say a district or a tract.
Unless the tweet was made from a mobile device it's lat/long is going to be where the ISP is registered. If I tweet from my desktop my tweets emanate from the street in front of the capitol here in Nashville. If I use my phone and I allow the twitter app to use my lat/long then that would be different. Trust me, I could instantly use the lat/long data in analysis of twitter streams and I wish it were that simple.
What you could do is add a jitter function that adds random displacement along both the x and y coordinate field to displace the tweets lat/long. Or you could grid it out. If you know how many of them you are getting you can figure out easily the bounding area of your grid and do it like that.

Resources