Google maps API is not using region hint [duplicate] - javascript

This question already has answers here:
Get only country specific result using google geocode api
(4 answers)
Closed 5 years ago.
I'm having problems telling the Google maps API to restrict the results from the geocoding service to a specific region.
A simple example reproducing the problem is here: http://jsfiddle.net/pqZGr/
The JavaScript code is really simple:
$(document).ready(function () {
var geocoder = new google.maps.Geocoder();
$("#name").autocomplete({
source: function (request, response) {
geocoder.geocode({ 'address': request.term, 'region': 'it' }, function (results, status) {
response($.map(results, function (item) {
return {
value: item.formatted_address
}
}));
})
}
});
});
I also specified the API URL as http://maps.google.com/maps/api/js?region=it&language=it&sensor=false besides the 'region': 'it' in the request.
The problem is the addresses returned by Google are not restricted (nor hinted) to Italy
For example if you search mil (the begininning of Milano) I get Circondario di Miltenberg, Germania and Milion, Alemdar Mh., 34122 Istanbul/Provincia di Istanbul, Turchia and reka Mil', Sacha-Jacuzia, Russia.
It's returning results (also, only three?) from all over the world, an nothing from Italy (even when there are multiple cities matching mil).
What am I doing wrong?
As a side note, is it possible to restrict the search only to the cities, and not to full addresses?
Thanks in advance.

It sounds like you really should be using the Google Places Autocomplete API standalone or built in to the Google Maps API.
The geocoding service isn't designed for autocomplete queries, and won't return the kind of results you're looking for. The region parameter is a hint like you said, but it's not a restriction so if there is no suitable "mil" in Italy, or there is a much better match elsewhere you'll get those results.
There's no way to restrict the results to just cities.

If you are using Google geocoder autocomplete with jQuery UI, you can edit one line in ui.geo_autocomplete.js, line 46, and add your region. It's not 100% precise, but will reduce the number of found addresses:
this.options._geocoder.geocode({'address': _address}, function(_results, _status)
Replace with:
this.options._geocoder.geocode({'address': _address + ' YOUR_REGION_HERE'}, function(_results, _status)

Related

Add a user inputted location to OpenStreetMap using Leaflet.js

I am trying to create a map of user-inputted locations, however to do this I need to convert inputted cities into their latitude and longitude. This allows me to easily plot them using Leaflet.js using L.marker(point).addTo(map)
Given the input of say "London" is there a way using the OpenStreetMap API to fetch these values?
here are very few API tools available that will do this task (from my research) without the need for an API key.
I want to avoid using the google maps API if possible and would appreciate any help, whether it be API recommendations or OpenStreetMap ideas, as I am relatively new to javascript.
Thanks in advance!
As recommended in the comments, the solution was to use nomination, in particular, their search queries.
I ended up using jQuery's getJson function to fetch the data from the API as follows.
$(function () {
geocoding = function (city, country) {
var url = `https://nominatim.openstreetmap.org/search?city=${city}&country=${country}&format=json`
$.getJSON(url, function (data) {
//data is the JSON string
lat = data[0].lat
lon = data[0].lon
...
});
}
})

How to get all place details from a Place Details Request using Google Places API Web Service?

I am trying to get data, like phone numbers, from a Place Details Request using The Google Places API Web Service. I am unable to get response data that is similar to the one shown in this guide, even though I'm getting the place id from the same address.
The place id I get is different from the one in the guide. My place id is 'ChIJ8UadyjeuEmsRDt5QbiDg720' and theirs is 'ChIJN1t_tDeuEmsRUsoyG83frY4'. If I use their place id I get all the data I need.
The only data I can get are: address_components, adr_address, formatted_address, geometry, icon, id, name, place_id, reference, scope, types, url, and vicinity. How can I get data like a phone number from a request?
var placesRequest = $http({
method: "post",
url: "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + <my place id>+"&key=<my key>"
});
placesRequest.success(function (data) {
console.log("data", data);
});
Same problem with Google Maps JavaScript API using this code.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.866, lng: 151.196},
zoom: 15
});
google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: $scope.newUserData.address.place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
if(place) {
console.log("place", place);
}
}
});
}
initMap();
The phone number is missing in the Google Places API because Google Maps doesn't have a phone number for that particular place. If you request the details for a place with a phone number on Google Maps, it will be returned.
Take a closer look at ChIJ8UadyjeuEmsRDt5QbiDg720. It's an office building called "Workplace 6" — notice that the details say it is of type premise. If you visit the Google Maps URL in the url field (https://maps.google.com/?q=Workplace+6&ftid=0x6b12ae37ca9d46f1:0x6defe0206e50de0e) you'll notice there's no phone number listed there either.
The other Place ID, ChIJN1t_tDeuEmsRUsoyG83frY4, is for one of the businesses located inside that building (Google). If you compare the address_components or formatted_address you'll see they don't have quite the same address (Google's address is floor 5 of that building).
In general, any field of a place might be absent. This happens if Google Maps doesn't know it, or if it simply doesn't apply (e.g. you won't find opening_hours on France). As the documentation for Place Details Results say:
Each result may contain the following fields:
[Emphasis mine.]

google maps geocoding changes

Has anyone noticed that google maps geocoding have changed the variable name of the lat and lng from, Qa and Ra to Pa and Qa.
Does anyone know a reason for this?
Edit: If you're using the Google Maps Geocoding Service, as #hamczu suggests, then you should be getting the results like this:
{
... snip ...
geometry: {
location: LatLng,
... snip ...
}
}
It sounds like you're not using the API methods for the LatLng object, but are instead trying to use its undocumented properties. Your question demonstrates one of the best reasons why this is a Bad Idea - the Google code is compressed and obfuscated, using short, arbitrary variable and property names, and Google may recompress its code at any time, arbitrarily changing these names. What it won't change is the function and attribute names in the published API - that's the whole point of having an API to begin with, and the reason why developers should code against the API, not the "undocumented features" of the currently available code.
So the best approach is to use the documented methods:
var lat = result.geometry.location.lat();
var lng = result.geometry.location.lng();
Otherwise, your code will likely break every time Google recompresses its code.

Using Google Geolocation JSON

I'm trying to use Google Reverse Geocoding, which takes some coordenates and returns a JSON structure with some addresses. My javascript code is like this:
$.getJSON("http://maps.google.com/maps/api/geocode/json?",
{ latlng: myDevice.Lat + "," + myDevice.Lon,
sensor: true},
function (data) {
...
}
)
However, when debugging with firebug, when it gets in the function, it turns out that data is null.
Could someone give me any advice?
Thank you!
You are likely bumping up against the Same-Origin Policy. You have two choices:
Create a server-side proxy to grab the data, then request it via AJAX.
Use the Google Maps API

merge autocomplete results from multiple sources

I am currently getting autocomplete results from a single source. If I wanted to also get results from a second source how would I go about this, and can I add the results on the fly (if one of the sources took longer).
For example this is a form field which is autocompleted using town names from geonames.org.
http://jsfiddle.net/Q6YFx/
How would I impliment merging the results from a second source such as Google Geocode API:
geocoder.geocode( { 'address': request.term, 'region': 'GB' }, function(results, status) {
response($.map(results, function(item) {
return {
value: item.formatted_address+' (google)',
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
The google results are quicker to fetch, so I'd like to show these when they are ready and then when I get the geonames.org results I'd like to add these to the mix.
Thanks
This is how I did it in the end http://jsfiddle.net/ekzMN/89/
Try adapting the code from this SO post:
jQuery UI autocomplete - multiple sources

Categories

Resources