A few people have asked this before but with no joy. But, it seems as though recently, google have offered the availability to fetch reviews from your google places via their api.
https://developers.google.com/maps/documentation/javascript/places
I have the url that shows the json of the exact google place I want, however, I cannot see an example on how to fetch the reviews only from this and am completely stuck. Their example shows how to show the map, but not how to fetch the reviews only. Has anyone done this? If so, is there an example of how to do it? Thanks.
Once you have the id of a place you can do
var request = {
placeId: 'place-ID-here' // example: ChIJN1t_tDeuEmsRUsoyG83frY4
};
var service = new google.maps.places.PlacesService(map); // map is your map object
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(place.reviews);
}
});
Update with full working example (https://codepen.io/gpetrioli/pen/OmQyEE)
var map, service;
function initMap() {
var central_park = new google.maps.LatLng(40.764243, -73.973049);
map = new google.maps.Map(document.getElementById("map"), {
center: central_park,
zoom: 14
});
var request = {
location: central_park,
radius: "500",
types: ["food"]
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, searchResult);
}
function searchResult(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// show first result on map and request for details
var place = results[0];
var marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title: place.name
});
var infowindow = new google.maps.InfoWindow({
content: place.name
});
infowindow.open(map, marker);
service.getDetails({placeId: place.place_id}, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
let reviewEl = document.querySelector('.reviews');
for (let review of place.reviews){
let li = document.createElement('li');
li.innerHTML = `<div>Author: ${review.author_name}</div>
<em>${review.text}</em>
<div>Rating: ${review.rating} star(s)</div>`;
reviewEl.appendChild(li);
}
}
});
}
}
* {
box-sizing: border-box;
}
#map {
width: 500px;
height: 400px;
}
.reviews {
padding:0;
list-style:none;
}
.reviews li+li {
margin-top: 1em;
padding-top: 1em;
border-top: 1px solid black;
}
.reviews em{display:block;margin:0.3em 0;}
<div id="map"></div>
<ul class="reviews"></ul>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDbDfZUthAGL2BW3jg9xhWglf6HLpJQ1AU&callback=initMap&libraries=places"
async defer></script>
You can use the Google Maps API:
https://maps.googleapis.com/maps/api/place/details/json?place_id=<place_id>&fields=reviews&key=<api_key>
More here: https://developers.google.com/places/web-service/details#PlaceDetailsResults
Related
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>
I'm looping through about 60 addresses to get them geocoded for use on a Google Map. My callback (below) seems to work well for collecting the locations, but I need to know how to relate them to the address objects I'm looping through. I can't find anything in the geocode response that tells me which of my requests it 'came from.'
Is there a way to do that?
This is my function:
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
});
}
In JavaScript you can use Immediately-invoked function expression that will create a function scope also known as closure. You should change your function to something similar to
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address}, (function(originalAddress){
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?
//You can use the originalAddress variable here to relate result to request
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
};
})(this.address));
}
}
Have a look at my example, it geocodes 3 addresses and print in console result and corresponding request string
var addresses = [
'av Diagonal 197, Barcelona',
'av Lucas Vega 53, San Cristobal de La Laguna',
'Metrologichna 14, Kiev'
];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
addresses.forEach( function(address) {
geocode(geocoder, address);
});
}
function geocode(geocoder, address) {
geocoder.geocode({'address': address}, (function(originalAddress) {
return function(results, status) {
if (status === 'OK') {
console.log("Search: " + originalAddress + "->" + results[0].geometry.location.toString());
} else {
console.log("Search: " + originalAddress + "->" + status);
}
};
})(address));
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">
</script>
I hope this helps!
I am trying to add pins to a Google Map using postcodes stored in a Google Sheet. So far I have been able to access to the Postcodes in the spreadsheet using JSON:
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v) {
var data = $('<div class="listing">').append('<h4 id="bandb">' + v.gsx$postcode.$t + '</h4>');
$('body').append(data);
});
});
I am also able to add pins to a Google Map using the postcodes.
Example: http://codepen.io/aljohnstone/pen/eJOyrP
I am having trouble combining the two. I would like the postcodes variable in the Codepen to take the postcodes from my Google Sheet.
Working example using the Google Maps Javascript API v3:
$(document).ready(function() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: {
lat: 54,
lng: -3
},
zoom: 5
});
var i;
var postcodes = [];
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v) {
postcodes.push(v.gsx$postcode.$t);
});
}).done(function() {
map.setCenter(new google.maps.LatLng(54.00, -3.00));
map.setZoom(5);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < postcodes.length; i++) {
geocoder.geocode({
'address': "" + postcodes[i]
}, (function(i) {
return function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: postcodes[i]
});
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}
})(i));
}
});
});
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<div id="map_canvas"></div>
Try this
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false" type="text/javascript"></script>
<div id="map_canvas" style="width: 600px; height: 350px"></div>
<script type="text/javascript">
$(document).ready(function()
{
var geocoder = new GClientGeocoder();
var map = new GMap2(document.getElementById("map_canvas"));
var i;
var postcodes = [];
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v)
{
postcodes.push(v.gsx$postcode.$t);
});
}).done(function()
{
map.setCenter(new GLatLng(54.00, -3.00), 5);
for (i = 0; i < postcodes.length; i++) {
geocoder.getLatLng(postcodes[i] + ', UK', function(point) {
if (point) {
map.addOverlay(new GMarker(point));
}
});
}
});
});
</script>
Working example http://codepen.io/snm/pen/eJOVMY?editors=101
I have two mysql tables: "cars" and "locations".
Cars are assigned to a locations by having field "location_id" in "cars" table. I am showing locations in a google maps retrieving coordinates from "locations" table.
What I would like to do, is to show in info window of google maps marker (which mark a location) which cars are assigned to this location.
I use get_locations.php with this code to retrieve information from DB:
$query_cars = "SELECT * FROM cars where location_lat not like ''";
$cars = $db->query($query_cars);
$row_cars = $cars->fetchAll(PDO::FETCH_ASSOC);
$query_locations = "SELECT id, name, gpslat, gpslong FROM locations where name not like '%/ Zona%' and status='Activa'";
$locations = $db->query($query_locations);
$rowLocations = $locations->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rowLocations);
Than I call this script from html page with this code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=API KEY">
</script>
<script type="text/javascript">
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.430013, -3.695854),
zoom: 12
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
makeRequest('get_locations.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
var image = 'http://www.bluemove.es/equipo/images/car_location_Normal.png';
function displayLocation(location) {
var content = '<div class="infoWindow">' + location.name; // content of the pop up window
if (parseInt(location.gpslat) == 0) {
geocoder.geocode( { 'address': location.address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.name,
incon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.gpslat), parseFloat(location.gpslong));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.name,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
So when marker is clicked, the location name is displayed on the info window. But as I said I also want to display car name that are assigned to this location.
Does anybody have any idea?
Thank you!
You have to make an INNER JOIN query so the $rowLocations will contain both table values.
Something like that:
SELECT * FROM cars AS c INNER JOIN locations AS l ON c.cars = l.location_id
WHERE c.location_lat NOT LIKE "'" AND l.name NOT LIKE '%/ Zona%';
I'm quite new to Google Maps API but while doing some research the other day I saw this.
https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple
Is it as easy as putting php into that contentString
I am using Google map api v3 to plot markers of location array. My script is
function OnSuccess(response) {
var markers = response.d.split('^^');
var latlng = new google.maps.LatLng(51.474634, -0.195791);
var mapOptions1 = {
zoom: 14,
center: latlng
}
var geocoder = new google.maps.Geocoder();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions1);
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
}
where markers variable is bringing proper data, my test data is array of 5 elements
The Game Larder, 24 The Parade, Claygate, Surrey,KT10 0NU
24 The Parade, Claygate, Esher, Surrey KT10 0NU
Card Collection, 14 The Parade, Claygate, ESHER, KT10 0NU
16A The Parade, Claygate, ESHER, KT10 0NU
and same is coming into array markers however it is plotting only two markers. What could be wrong here
Solution
I was entering locations which are very close to each other e.g 1 and 2 point which gives same latlong hence mark as one place. I found latlong here. Thanks for answers btw :)
In page.aspx. insert tag <div id="map-canvas" ></div>
view source page.aspx and insert script into it>
var lis_marker = new Array();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
lis_marker[i] = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
there are difference with your code:
1: var lis_marker = new Array();
2: lis_marker[i] = new google.maps.Marker({...});