How to attach .then on on google maps places library services - javascript

https://developers.google.com/maps/documentation/javascript/places
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
type: ['restaurant']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
This is the approach google has mentioned in their docs
But I need to return the result sent by service.nearbySearch to callback(results, status)
Insteed of using callback I wanna do it using .then or await
something like
Get result of service.nearbySearch into variable (e.g. result__ )
let result__ = await service.nearbySearch(request);
or
service.nearbySearch(request)
.then(()=>{})

Related

Google Places API only returning 1 result

We saw in a similar question that the Places API should return up to 5 results, but right now we are only able to get 1 result. We were following the tutorial to display museums in Sydney. Does anyone know how to display more than one result? The script for the Maps and Places API is below.
let map;
let service;
let infowindow;
function initMap() {
const sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), {
center: sydney,
zoom: 15
});
const request = {
query: "Museum",
fields: ["name", "geometry"]
};
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
const marker = new google.maps.Marker({
map,
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name);
infowindow.open(map);
});
}
From the documentation:
Find Place from Query takes a text input and returns a place.
(note the singular "a place")
To get multiple results use nearbySearch (or textSearch)
const sydney = new google.maps.LatLng(-33.867, 151.195);
var request = {
location: sydney ,
radius: '10000',
type: ['museum']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
proof of concept fiddle
code snippet:
"use strict";
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&libraries=places">
let map;
let service;
let infowindow;
function initMap() {
const sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), {
center: sydney,
zoom: 15
});
var request = {
location: sydney ,
radius: '10000',
type: ['museum']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("places service returned "+results.length+" results");
document.getElementById('info').innerHTML = "places service returned "+results.length+" results";
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
const marker = new google.maps.Marker({
map,
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name);
infowindow.open(map);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Place Searches</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly"
defer
></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="info"></div>
<div id="map"></div>
</body>
</html>

Google Maps google.maps.places.PlacesService typeerror undefined

Following the code nearly exactly from: https://developers.google.com/maps/documentation/javascript/places#TextSearchRequests
When
service = new google.maps.places.PlacesService(map);
is called, the console gives me an undefined type error:
util.js:22 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
My code is below. Anyone know what is happening?
HTML
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDo5LxyVUv5EwGQBwaveIF4d0MaIVD_Dd8&libraries=places"></script>
JS
function initMap(userLocation) {
map = new google.maps.Map(document.getElementById('map'), {
center: userLocation,
zoom: radius
});
infowindow = new google.maps.InfoWindow();
}
function textSearch(query) {
var service;
var request = {
location: userLocation,
query: query
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, cb);
}
function cb(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
// createMarker(results[i]);
console.log(place);
}
}
}
initMap(userLocation); // userLocation is a latLong obj, set elsewhere in the code.
textSearch('movies');

How can I implement promises to deal with multiple Google Places API calls?

I have an Angular.js service which retrieves a number of Place search results from the Google Places API. The service then proceeds to call a detailed place request for each result. I am trying to then pass the resulting JSON back to a controller.
I believe that due to the asynchronous nature of the API calls, the detailed results are not all returned. When I log the returned places from the ResultsActivity, I can see that not all of the results are there. I can however see on the console that the results are returned after the promise has been resolved. I have tried to implement multiple promises and $q.all(), but to no avail.
I would be grateful if someone could point me in the right direction as to how to use $q.all or suggest a better approach to this.
Thank you.
PlaceService:
// public/js/services/PlaceService.js
angular.module('Services').factory('PlaceService', ['$http', '$rootScope', '$location', '$q', function($http, $rootScope, $location, $q){
var map;
var service;
var infowindow;
var basicPlaces = [];
var places = [];
function getPlaces(lat, lng, radius){
var deferred = $q.defer();
var promises = [];
function initialize(lat, lng, radius) {
console.log('initialize');
var pyrmont = new google.maps.LatLng(lat,lng);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 12
});
infowindow = new google.maps.InfoWindow();
var request = {
location: pyrmont,
radius: radius,
types: ['store']
};
service = new google.maps.places.PlacesService($("#results")[0]);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
console.log(results[i]);
$("#results").append('<p>'+results[i].name + '\n\n</p>');
createMarker(results[i]);
basicPlaces.push(place);
var defer = $q.defer();
promises.push(defer);
service.getDetails({
placeId: results[i].place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(place);
places.push(place);
console.log(places);
console.log(i);
if (i == results.length) {
console.log("deferring");
defer.resolve(place);
}
}
});
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
initialize(lat, lng, radius);
return $q.all(promises);
}
return {
getPlaces
}
}]);
Calling the service from the ResultsActivity:
PlaceService.getPlaces($scope.latitude, $scope.longitude, $scope.radius).then(function(places){
$scope.places = places; //Some detailed places are missing here
});

Get total marker count from Google API placesSearch

In the example fiddle, how can I get the total number of markers displayed on the map? I'm pushing each of the markers into an array like this:
markers.push(marker)
And attempting to get the total number of markers like this:
$('.marker-count span').html(markers.length);
Unfortunately, "markers.length" is returning 0 when it should be returning at least 3.
I have example code here: http://jsfiddle.net/287C7/
How can I display the total number of markers? Is it not possible to add each marker to my array?
I need to know the amount of markers shown so that I can alert the user if there are none.
Thanks,
In case you don't want to view the code on jsfiddle.net, here it is:
var map, places, tmpLatLng, markers = [];
var pos = new google.maps.LatLng(51.5033630,-0.1276250);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(51.5033630,-0.1276250)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// create the map and reference the div#map-canvas container
var markerBounds = new google.maps.LatLngBounds();
var service = new google.maps.places.PlacesService(map);
// fetch the existing places (ajax)
// and put them on the map
var request = {
location: pos,
radius: 48000, // Max radius
name: "mc donalds"
};
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
function createMarker(place) {
var prequest = {
reference: place.reference
};
var tmpLatLng = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
markerBounds.extend( tmpLatLng );
} // end createMarker
service.nearbySearch(request, callback);
the placesSearch call is asynchronous, when you run your code:
$('.marker-count span').html(markers.length);
the result hasn't come back from the server yet. You need to do that in the call back after you update the markers array.
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
working fiddle

get place within the given lat and long in ajax

i am in a trouble to find the places within the lat, long and radius using ajax or javascript , i used a ajax code to find this but getting error,
my code is :
$.ajax({ url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?',
data: {
location:'-33.8670522,151.1957362',
radius:500,
sensor:false,
key:'AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I'},
dataType: "json",
type: "GET", //or POST if you want => update your php in that case
success: function( data ) {
for(var i in data.results){
alert(data.results[i]);
}
},
error: function (request, status, error) {
alert("error");
//handle errors
}
});
it gets the result error, please help me to find this
Thanks
try the following code to get places from near by locations
function initialize(arg)
{
directionsDisplay = new google.maps.DirectionsRenderer();
mapmarker="img/pois/"+arg+".png";
geocoder = new google.maps.Geocoder();
var location = new google.maps.LatLng(11.21989,78.16811099999995);
map = new google.maps.Map(document.getElementById('googleMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: location,
zoom: 15
});
directionsDisplay.setMap(map);
var request = {
location: location,
radius: '5000',
types: [arg]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
//google.maps.event.addDomListener(window, 'load', initialize);
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
var place = results[i];
createMarker(results[i]);
}
}
}

Categories