I'm using the google places JavaScript API to get place details.
I am encountering two issues to do with JavaScript:
The first is extracting user reviews from the place.reviews array
I can get the place.name, place.phone, and place.formatted_address values but I am unable to retrieve the reviews from the place.reviews array.
I found some sample code on the link below to loop through the reviews array but I can't get it to work. I get script errors for example with the keyword forEach.
Google Places JS API Show Reviews
Is there an easy way to retrieve the values from the reviews array?
These are the script declarations at the top of my HTML document:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
The Second
I am creating a simple search app so I can view what's around me. I would like to add the distance and time from the start location to the venue the user clicks on i.e. 'London Bridge = 1 km, 10 mins'.
I can get the time and distance values using the Google matrix distance API using a callback function but I don't know how then to pass the values to the main part of my code.
I have had a look at some answers on here but I am still confused about how callback functions work:
function createMarkers(results, PlaceSearchStatus) {
var resultcontent = ''; //stores place results to be displayed on map
var resultdiv = document.getElementById('searchresults');
if (PlaceSearchStatus == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
//use the Distance Matrix API to get the distance between this venue and start location
/distancematrix#distance_matrix_responses
var DistanceService = new google.maps.DistanceMatrixService();
var origin1 = new google.maps.LatLng(document.getElementById('lat').value, document.getElementById('lng').value);
var destination1 = results[i].geometry.location;
DistanceService.getDistanceMatrix({
origins: [origin1],
destinations: [destination1],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, DistanceMatrixStatus) {
if (DistanceMatrixStatus != google.maps.DistanceMatrixStatus.OK) {
alert('Distance matrix API Error was: ' + DistanceMatrixStatus);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
//getting the distance value gives more accurate results than the text value but not using that
//alert(results[i].distance.value + ", " + results[i].duration.value);
//get the time and distance to this location from our start location
// Need to fix. this isn't working as this is inside a callback function.
var TimeAndDistance = results[i].distance.text + ", " + results[i].duration.text;
}
}
} // end of distance matrix code
//concatonate the accessible search results and add on the time and distance to the place name
resultcontent += '<p> <h2>' + '<div <input id=\"button2\" type=\"button\" class=\"button\" value=\"' + results[i].place_id + '\" onclick=\"GetIndividualPlaceDetails(this);\">' + results[i].name + '</div> </h2>';
Thanks,
Tom
The following code works for accessing the reviews and I'm using another work around for my second question:
len = place.reviews.length;
for (i=0; i<len; ++i) {
resultcontent += place.reviews[i].rating + ' stars';
resultcontent += ', On ' + place.reviews[i].time + ' ' + place.reviews[i].author_name + ' said:';
if (!!place.reviews[i].text) resultcontent += '<br />' + place.reviews[i].text;
}
}
Related
Any advice on how to adjust this piece of code, so that it pushes the coordinates of a first vertice of a polygon (sort of repeats it) in the end to make it ready for kml files?
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
for (var i = 0; i < polygon.getPath().getLength(); i++) {
document.getElementById('info').innerHTML += polygon.getPath().getAt(i).lng() + ',' + polygon.getPath().getAt(i).lat() + ',0' + ";";
}
polygonArray.push(polygon);
});
It's relatively easy to push the coordinates of a first vertice and make them display after every iteration of the loop but I wanted them to be added once and after the last unique vertice.
Now I am getting this:
17.38037109375,52.60971939156647,0;
17.314453125,51.89683388301249,0;
18.731689453125,52.456009392640766,0;
and would like to get this:
17.38037109375,52.60971939156647,0;
17.314453125,51.89683388301249,0;
18.731689453125,52.456009392640766,0;
17.38037109375,52.60971939156647,0;
I would appreciate a liitle help on that.
Thank you.
If you want to append the first coordinate to the end of the string in the "info" div, just add it to the end:
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
for (var i = 0; i < polygon.getPath().getLength(); i++) {
document.getElementById('info').innerHTML += polygon.getPath().getAt(i).lng() + ',' + polygon.getPath().getAt(i).lat() + ',0' + ";";
}
document.getElementById('info').innerHTML += polygon.getPath().getAt(0).lng() + ',' + polygon.getPath().getAt(0).lat() + ',0' + ";";
polygonArray.push(polygon);
});
My goal is to automate process of route calculation from A to B in Google Maps by using JavaScript + Google Distance Matrix Service. I would like to find route which is the fastest (based on current traffic). Script should calculate route by using current date and time.
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function init() {
var service = new google.maps.DistanceMatrixService;
var origin = 'Great,Lake,8';
var destination = 'Lake,Great,21';
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
drivingOptions: {
departureTime: new Date(Date.now()), // for the time N milliseconds from now.
trafficModel: "best_guess"
}
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
<!-- The same accessing of elements in object
-->
<!-- document.getElementById("result").innerHTML += '1)' + JSON.stringify(response.rows[0].elements[0].distance.text) + '<br>';
document.getElementById("result").innerHTML += '2)' + JSON.stringify(response.rows[0].elements[0]['distance']['text']) + '<br>';;
document.getElementById("result").innerHTML += '3) RESPONSE: ' + JSON.stringify(response) +'<br><br>'; -->
document.getElementById("result").innerHTML += 'RESULT: ' + JSON.stringify(response);
alert(response.originAddresses[0] + ' ' + response.destinationAddresses[0] + ' ==> ' + response.rows[0].elements[0].duration.text + ' ' + response.rows[0].elements[0].distance.text);
}
});
}
</script>
<body onload="init()">
<div id="result">
</div>
</body>
Code works only if drivingOptions is removed. But I need this object - because I would like to calculate route based on traffic situation. I am executing script in https://jsfiddle.net/ - so I don't see any errors - except that when I removed drivingOptions object I saw that pop up with time and distance shown in pop up.
I am having an issue with Google Maps cluster function. It is correctly clustering and placing cluster counts on the map and the cumulative counts total the correct number of locations/markers given it. But no icons are showing when the count of the locations within a given cluster is greater than 9 (or greater than 1 digit count). Does anyone have an idea how to correct this? I am using the "standard" Google Maps blue icons for the clusters. The blue icon shows for a cluster of 4 markers. But the clusters of 132 and 79 markers only display the 132 and 79 counts -- no blue icons. I don't have a convenient place to quickly put a screen capture for public consumption.
var tableContent = "";
$.each(data, function (i, item) {
iCount++;
var aCount = iCount.toString();
var iCt = item.RECNO;
//table += "<tr><td>" + '(' + aCount + ') ' + item.DDSPNM + "</td></tr>";
tableContent += '<tr>';
var rowContent = "";
rowContent += "<strong>" + item.DDSPNM + "</strong>" + "<br>"
rowContent += item.DCTRNUM;
tableContent += '<td>' + rowContent + '</td>';
tableContent += '</tr>';
var latlng = new google.maps.LatLng(item.Latitude, item.Longitude);
locations.push(latlng);
var marker = new google.maps.Marker({
position: latlng,
label: { text: aCount, color: 'black', fontSize: "12px" },
title: 'this is ' + item.DDSPNM,
map: map
});
gmarkers.push(marker);
});
if (iCount == 0)
{
table += "<tr><td>No providers were found in the specified location. Please change your search criteria and try the search again.</td></tr>";
tableContent += "<tr><td>No providers were found in the specified location. Please change your search criteria and try the search again.</td></tr>";
}
$('#results').append(tableContent);
// Instantiate pagination after data is available
pager = new Pager('results', 10);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
// set the bounds for the map and re-size/re-position to display all markers
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
bounds.extend(locations[i]);
}
map.fitBounds(bounds);
var markerCluster = new MarkerClusterer(map, gmarkers,
{ imagePath: #Url.Content("~/Images/m")});
}
Please ignore what is ugly presentation for the user, that's the piece I am working on now. But I'm stumped as to why icons for clusters don't show when the count is greater than 9 (or greater than 1 digit).
Sorry for clogging up the works with this question. All I can say is duh...I thought all of the icons were enabled in my VS project and that is wrong. All I can say is that once I enabled all icons the yellows, reds, etc. starting appearing with multiple digit counts.
Sorry for personal screw up!
Let's say you have a map to display KmlLayer objects on it, with toggle checkbox for each KmlLayer object, located in a panel.
var Province = new google.maps.LatLng(47.112754, -70.815223);
var map = new google.maps.Map( document.getElementById('map'), {zoom:7,center:Province} );
And you store in KML files a limited number of routes, to optimize the speed of the map.
Direction's requests are made using Google Maps API v3.
And let's say you have a page containing a Google Map in a hidden div, and you make Direction requests through this API.
The array 'waypoints' holds the coordinates of each start and end point of each polyline needed.
var geo_coords = ''; // holds the results
var y; // counter
var delay_per_request = 1000; // default delay in milliseconds between requests
var current_delay = delay_per_request; // current delay between requests
function calcRoute(start,end) {
setTimeout(function(){
var directionsService = new google.maps.DirectionsService();
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
// Error?
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
document.getElementById('error_text').innerHTML += "<br>" + start + "/" + end
+ "("+status+") :: Interval:"+current_delay+"ms";
window.scrollTo(0, document.body.scrollHeight);
if (current_delay < 2600) {
current_delay += 200;
}
if (current_delay >= 1600) {
delay_per_request = 1600;
}
retry++;
if (retry < 20) {
calcRoute(start,end);
} else {
document.getElementById('error_text').innerHTML += "<br>The script stopped running after "+retry+" retries"
+ " sur " + start + "/" + end + "("+status+") :: Interval:"+current_delay+"ms";
}
// Positive result?
} else if (status == google.maps.DirectionsStatus.OK) {
var myRoute = response.routes[0].overview_path;
for (i in myRoute) {
if (myRoute[i] != undefined) {
geo_coords += myRoute[i].lat() + "," + myRoute[i].lng() + "_";
}
}
geo_coords += "!";
document.getElementById('error_text').innerHTML += "<br><font color=\"green\">" + start + "/" + end
+ "("+status+") :: Interval:"+current_delay+"ms</font>";
window.scrollTo(0, document.body.scrollHeight);
current_delay = delay_per_request;
retry = 0;
Next();
}
});
},current_delay);
}
function Next() {
if (y <= waypoints.length) {
destination = "from:" + waypoints[y] + " to:" + waypoints[y + 1];
geo_desc += description[y] + " => " + description[y+1] + "|";
calcRoute(waypoints[y],waypoints[y+1]);
y = y +2;
} else {
document.getElementById("information").setAttribute('value',geo_coords);
document.getElementById("show_debug_text").setAttribute('value',geo_desc);
document.getElementById("error").setAttribute('value',document.getElementById('error_text').innerHTML);
document.forms["kml"].submit();
}
}
Next();
My question is the following:
Has anyone noticed that Google lower the priority of your requests after you made some request in batch?
The more request you do, the bigger is the number of OVER_QUERY_LIMIT response you get, the bigger is the delay between requests before you have a successful result, and the bigger is the number of requests before you have a successful result.
Is there any workaround or any reason?
(I know I should use the Direction API Webservice to make my requests.)
Thank you!
I have images to overlay on google maps by using checkboxes. I made this script to not create the separate individual script for each overlay but it returns the error of proprty not supported in main.js of google maps api. However, i tried getting the output value in javascript alert and it returns the values as expected. Could anyone help please?
Here is the script.
function shImg(url,lat,lng) {
var lat_ = "new GLatLng(" + lat + ")";
var lng_ = "new GLatLng(" + lng + ")";
var latlng = lat_ + ", " + lng_;
var ticked_ = document.getElementById(url);
var boundaries_ = "new GLatLngBounds(" + latlng + ")";
var imgurl_ = "http://www.mywebsite.com/" + url + ".jpg";
imageOverlay_ = new GGroundOverlay(imgurl_, boundaries_);
map.addOverlay(imageOverlay_);
if (!ticked_.checked) {
map.clearOverlays();
// imageOverlay_=null;
}
else {
alert(boundaries_);
imageOverlay_.show();
}
}
The GLatLng constructor takes two arguments, a latitude and a longitude. Similarly GlatLngBounds takes two arguments, a GlatLng for the south west corner and one for the north east. See the api docs for more info.
Lastly why are you doing string concatenation all over the place? For example "new GLatLng(" + lat + ")"; should be new GLatLng(lat,lng);