nearby places in google maps api - javascript

I have to develop a website on which user enter latitude and longitude of a particular location. based on latitude and longitude I should fetch nearby locations and display it on google maps. As of now, I displayed the nearby locations for one type eg.restaurants, Now I want to fetch more than one type using place-API.

Unfortunately, neither searching with multiple types nor excluding a type from query is possible right now. Google's policy is simply forcing people to send more requests. Sometimes people pay for things they don't want or double/triple for what they could achieve with only one query.
Although there's no searching option for second,third parameter, you can still get what you want, with of course paying for it.
This is how a regular NearbySearch request looks like;
var service = new google.maps.places.PlacesService(map);
let latLng = new google.maps.LatLng(latitude,longitude);
service.nearbySearch(
{location: latLng, radius: 500, type: ['store']},
function(results, status) {
if (status !== 'OK') return;
// results
};
});
If you want to get multiple types, you have to send a request for each type which would look like this;
var service = new google.maps.places.PlacesService(map);
let latLng = new google.maps.LatLng(latitude,longitude);
service.nearbySearch(
{location: latLng, radius: 500, type: ['store']},
function(results, status) {
if (status !== 'OK') return;
// results for store
service.nearbySearch(
{location:latLng, radius: 1500, type : ['fire_station']},
function(fireStationResult, fireStationStatus) {
// firestation results here
// and so on.
}
)
};
});
You have to use nearbySearch request in eachother's blocks since it work async.

Searching for multiple types is not currently supported by the Places API's Nearby Search.
There is an existing feature request for this: https://issuetracker.google.com/issues/112291747. I'd recommend you to comment your use-case in there and star it to receive updates.

Related

Highlight an existing business on Google Maps API

I have a list of store addresses, and I'm trying to create a map out of it.
Using the Places API I am able to retrieve most of the informations and manually create and place the markers on the map:
const service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery({
query: '212 Enterprise Dr, Rockaway, Frank Pizza',
fields: ['all']
}, onPlaceFound);
However I'd like to select the original marker instead of overlapping a new one.
That is because I want the user to be able to open the default info window with store phone number, directions and stuff.
I know that I can re-create it, but it feels kinda lame since all the info is already there.
This SO post ask about the same, yet no solution has been found.
Based on the documentation found here, which shows findPlaceFromQuery(), the second parameter of findPlaceFromQuery should be a function where the first argument of that function is an Array of placeResults.
Therefore, after reviewing a link here and here your onPlaceFound function should be looking something like:
function onPlaceFound(placeResultsArray){
const firstResult = placeResultsArray[0], firstIconURL = firstResult.icon;
const latLng = firstResult.geometry.location, lat = latLng.lat(), lng = latLng.lng();
// do stuff with those variables here
}
Of course, that does not select Google's result as a Marker, but now you have the actual icon, and latitude and longitude.

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

Edit an optimized Google Maps route

Desired functionality
After gathering pre-defined Start, End and intermediate Waypoints from a database, query the Google Maps API V3 to:
a) Optimize a route based on the Waypoints given.
b) Display such route on a Map. Display the optimal waypoint order.
c) Give the user the possibility to edit the order of waypoints. Please note: It is not desired to drag the waypoint´s marker to change it´s address. The desired behaviour is to have a list of waypoints as ordered by the API and then to be able to manually edit the order and update the map accordingly.
d) Save back to the database the final order after the API´s answer and the user´s possible edits.
What is currently working
Functionality described in points A and B is covered by the following code:
function initialize() {
var mapOptions = {
zoom: 8, <!-- We can also support customizable zoom levels according to the size of delivery area !-->
center: region
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Chemnitz, Germany', <!-- This will be the main address, we get it from the database. -->
destination: 'Chemnitz, Germany',
optimizeWaypoints: true,
waypoints:[{location: 'Mittweida, Germany'}, {location: 'Zwickau, Germany'}, {location: 'Dresden, Germany'}, {location: 'Freiberg, Germany'}], <!-- This will be the list of locations the truck has to visit, we get it from the database. -->
travelMode: google.maps.TravelMode.DRIVING <!-- Maps supports many types of transport, but we have to specify this is a particular vehicle. -->
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Question
Is there any method in the API to support manual editing of the waypoint´s order after the API has optimized and displayed them?
Are there any examples of similar solutions that might help me resolve this issue?
Additional information
The reason why I need to support manual editing of the waypoint´s order is that sometimes, there are time constraints for the deliveries these stopovers represent. Therefore, occasionally the user will want to modify the stopovers order to make them more suitably delivered at a convenient time, i.e.: the end of the day, the beginning of the route in the morning, etc.
Thanks in advance for any help.
There is no built-in implementation for this, but it's not difficult to achieve it.
The order of the optimized waypoints may be retrieved via the waypoint_order-property of a route. You may use this order to create a sortable list, when the list will be re-ordered send a new request with the re-ordered waypoints and the optimizeWaypoints-option set to false

Fetching data from database every five seconds to Google Map

I am developing a Google maps application, latitudes and longitudes are coming from external device and storing into the database for every five seconds.
So I have to query the database every five seconds and get the new latitude and longitude of the database and moving the marker according to that.
How it can be done? Is it good to write ajax call?
Here is an example that pulls data every few seconds and replots the markers: http://www.robotwoods.com/dev/so_septa.html
here's the PHP it's calling:
<?php
$route=(isset($_REQUEST['route']))?$_REQUEST['route']:23;
echo file_get_contents("http://www3.septa.org/transitview/bus_route_data/".$route);
?>
I will guide you in the right way. I guess I could do that atleast:
a) You could have a function that queries your server at intervals using ajax (check out a library like jquery) and in the callback function of the function process the response.
b) your server will send a response to the server Ideally it will be a json response of the form
{
id:<>,
lat:
lng:
}
c) walk through google maps api to see how you can remove markers etc. you can probably maintain hash of markers in an associative array like markers[key] where key will be the identifier of a marker, if and when the marker updates you can use this associative array to remove the marker as:
markers[id].setMap(null);
Code to add markers in callback:
var options = {
position: new google.maps.LatLng(lat, lng);,
icon: image,
zIndex: zIndex,
};
options.map=map;
var marker = new google.maps.Marker(options); //construct marker
markers[key] = marker; //store the marker in array

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