Get ZIP codes of particular country using google map - javascript

I am using maps.googleapis.com/maps/api in codeigniter to display auto complete location when user types zip address. I have two input field from first user will select country and in second filed he will type his zip code and from google autocomplete he will select his address.
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('zip'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
It is working fine but now I want to show zip codes only from selected country. Means if user select Australia as country and type zip like 2127 then google api should show addresses in Australia having 2127 in address

Google maps JS api provides two kinds of widgets for autocomplete. One is google.maps.places.SearchBox you are using, which only offers restriction by Latitude and Longitude bounds and then there is google.maps.places.Autocomplete which provides country restriction (and much more), eg. like this:
var input = document.getElementById('searchTextField');
var options = {
componentRestrictions: {country: 'au'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
For more information about advantages/disadvantages of both approaches see the docs (check section "Summary of classes") and choose the best approach for your needs.

I would also add to previous answer that there is a feature request in the public issue tracker to extend components restrictions for places autocomplete (make it similar to Geocoding API)
https://code.google.com/p/gmaps-api-issues/issues/detail?id=4433
If you are interested in this feature request please star it to express your interest and receive updates from Google.

Related

How can i get address components using Google's AutocompleteService via JavaScript?

Google offers different ways to use the Place Autocomplete API. Two of these being the Autocomplete and AutocompleteService classes. Whenever I use the Autocomplete class I get the address components without a problem. However, whenever I use the AutocompleteService the address components are missing. I do get an address but not in the same way I do with Autocomplete (I can parse into city, street, state, etc.).
Is there a way I can get the address components field using AutocompleteService WITHOUT making an additional call with the place ID ?
Autocomplete example
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete(document.getElementById('search'), {
componentRestrictions: { country: ["us", "ca"] },
fields: ["address_components", "geometry"],
types: ["address"],
});
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace(); // Includes Address Components and Geometry (Lat and Lng)
});
}
AutocompleteService example
function initAutocompleteService() {
const service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
input: "1600 Amphitheatre",
componentRestrictions: {
country: 'us'
},
types: ['address']
}, (predictions, status) => {
console.log(predictions); // It shows the address a single string but missing address components
});
}
Is there a way I can get the address components field using AutocompleteService WITHOUT making an additional call with the place ID ?
Short answer: No, you can't.
If you are worried about billing, you should use Session tokens.
As per the documentation:
AutocompleteService.getPlacePredictions() uses session tokens to group together autocomplete requests for billing purposes.
The interesting part:
You can use the same session token to make a single Place Details request on the place that results from a call to AutocompleteService.getPlacePredictions(). In this case, the autocomplete request is combined with the Place Details request, and the call is charged as a regular Place Details request. There is no charge for the autocomplete request.
Google provides an example on how to create the Session token:
// Create a new session token.
var sessionToken = new google.maps.places.AutocompleteSessionToken();
// Pass the token to the autocomplete service.
var autocompleteService = new google.maps.places.AutocompleteService();
autocompleteService.getPlacePredictions({
input: 'pizza near Syd',
sessionToken: sessionToken
},
displaySuggestions);
When user selects a place, you can reuse that same session token to retrieve the place details with the fields you are interested in, in order to get billed only for the place details request (as stated above).
You might also want to read Cost optimization best practices.
Programmatic implementation
Use a session token with your Place Autocomplete requests. When requesting Place Details about the selected prediction, include the following parameters:
The place ID from the Place Autocomplete response
The session token used in the Place Autocomplete request
The fields parameter specifying the place data fields you need
As you can see, the PlaceDetailsRequest interface takes an optional sessionToken parameter.

Google autocomplete API returns places in my state first instead of the most "expected" places

I am using Google Autocomplete when entering addresses, this is the simple implementation:
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('origin_address'), {types: ["geocode"]}
);
When I start typing "Lon", the first suggested place is Long Beach, CA, and the next one is "London United Kingdom" - that's just an example.
I am located in California. Generally said, when I start typing an address, the places that are offered to my are located in CA. How do I get offered the places in the whole North America?
I tried to modify my autocomplete setup, like:
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('origin_address'), {types: ["route", "geocode"]}
);
But in this case the autocomplete didn't offer anything (even when I kept in the array only route.
How to set up autocomplete to suggest the places not mainly from CA, but from the North America?
Try this:
navigator.geolocation.getCurrentPosition(position=> {
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ position.coords.latitude + "," + position.coords.longitude
+ "&sensor=false").then(data=> {
for (let component of data.results[0].address_components) {
if (component.types.includes("country")) {
new google.maps.places.Autocomplete(
$('#origin_address')[0], {types: ["geocode"],
componentRestrictions: {country: component.short_name}}
);
break;
}
}
})
})
Firstly it gets current location using broswser's Geolocation API. Then it makes request to Google Maps API to get the country based on latitude and longitude. Then it initializes autocomplete, limiting it to this country.
See JS Fiddle demo.

Google Places using Geocoding

I have a database which contains a list of point of interests with latitude and longitude information. This data is not from Google Places.
I would like to get the information of the opening hours of the places based on their geolocation. Is it possible to do that using Google Places API ?
I have tried using Google Maps Geocoding API to get the place_id for given geocoding and then used Google Places API Web Service for getting the detail information of the place based on the place_id. However, it does not get the opening hours.
I wonder how to get the detail of a place using geocoding ?
For example in HERE using autocomplete place search, it is able to return the detail information about the place. However when I right clicked on the marker and copied the geolocation using what's this and tried to use Google Places API Web Service to query the detail of the place, some information is missing, for example, opening hours of the place.
For example Gyeongbokgung Palace the latitude and longitude stored in database is 37.5802 and 126.977 respectively as shown in the picture, the location from Google Maps is different even though they are not that far from each other.
With the Place details you can get all details for a specific place.
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(0, 0),
zoom: 15
});
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJod7tSseifDUR9hXHLFNGMIs' // Gyeongbokgung Palace
}, function (place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(place); // Log the place object
}
});
}
Below is a complete example on how to retrieve the opening hours for the place you mentioned.
JSFiddle demo

Google Maps API JS - Place autocomplete with two combined fields

I come to you because I can not use the autocomplete place function instead of Google maps JS api v3 as I would like.
Indeed, I would like to implement autocompletion on a field by adding the value of another.
Concretely, I would like to have two fields, one for the company name, the other for the address. I would like autocompletion is performed only on the address fields but taking into consideration the company name.
So if I fill "Company XYZ" in the company field and "New York, USA" in the address, it should lookup "Company XYZ, New York, USA".
Classical example with one input :
Function JS :
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('addr')),
{ types: ['establishment', 'geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
HTML Form :
<input class="field" id="company_name" />
<input class="field" id="addr" />
In your opinion is it possible? If so, how?
With thanks.
You can use the Autocomplete Service and get query predictions for the values of both fields.
See https://developers.google.com/maps/documentation/javascript/examples/places-queryprediction
var autocompleteService = new google.maps.places.AutocompleteService();
getPlacePredictions(document.getElementById('company').value + ', ' + document.getElementById('address').value);
function getPlacePredictions(search) {
autocompleteService.getPlacePredictions({
input: search,
types: ['establishment', 'geocode']
}, callback);
}
Below is a full example of a custom autocomplete predictions list (styled based on Google implementation), with search highlighting, place details request and display on the map with a marker.
JSFiddle demo

Google Places API Nearby Search to return custom data

Referring from the Google Places API Nearby Search Requests sample code below:
///......
var request = {
location: pyrmont,
radius: '500',
types: ['store']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
//....
Is it possible to request a custom lists of store data that is coming from a database for example?
If not, then what could be the best alternative?
Any help is greatly appreciated. TIA
source: Nearby Search Requests
No, all of the request data comes from Google using their Places API. In order to request custom data, you would have to roll your own search function to look through the database.
Have a look at SO: PHP AJAX Database search for one example of how to search a database for values (This one performs autocomplete based on input)

Categories