how to get place detail in google map - javascript

I am working on application in which i want place id for specific name which i am passing in request and want to get all places ID
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var data;
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
data += "The data is " + results[i] + "<br>";
}
document.getElementById('place_name').innerHTML = data.name;
//document.getElementById('place_id').innerHTML = data.place_id;
//document.write(data);
}
}
function createMarker(place) {
// var placeLoc = place.geometry.location;
//document.getElementById('place_name').innerHTML = place.name;
var marker = new google.maps.Marker({
map: map,
// placeId: place.place_id,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address);
// infowindow.setContent(place.address_components);
infowindow.open(map, this);
});
I am able to print name and id in marker but i just want to get all place id.
any help will be appreciated.
thanks in advance

this link from google could help you:
https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder?hl=es
Good look.

Related

Get PlaceID from nearbySearch and display in a marker InfoWindow ( JS Google Maps API )

I have this query
var service = new google.maps.places.PlacesService(map);
var request = {
location: currentLocation,
radius: '4828.03',
type: ['workout gyms']
};
service.nearbySearch(request, callback);
And I am able to successfully place a marker on every location, but I want to make the marker clickable such that it displays the placeID in an infoWindow when clicked. Does anyone know how I could do this?
Modified code from the related question: Place nearbySearch Callback doesn't iterate through all elements (to return place details)
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("nearbySearch returned " + results.length + " results")
for (var i = 0; i < results.length; i++) {
// make a marker for each "place" in the result
createMarker(results[i]);
}
} else console.log("error: status=" + status);
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
// display the place "name" and "place_id" in the infowindow.
infowindow.setContent(place.name + "<br>" + place.place_id);
infowindow.open(map, this);
});
}
modified fiddle
code snippet:
function initMap() {
var lng;
var lat;
var my_loc = new google.maps.LatLng(37.4419, -122.1419);
map = new google.maps.Map(document.getElementById('map'), {
center: my_loc,
zoom: 10
});
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
var request = {
location: map.getCenter(),
radius: 4828.03,
type: ['workout gyms']
};
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("nearbySearch returned " + results.length + " results")
for (var i = 0; i < results.length; i++) {
var id = results[i].place_id;
createMarker(results[i]);
}
} else console.log("error: status=" + status);
}
function createMarker(place) {
console.log("adding place " + place.name + " loc=" + place.geometry.location.toUrlValue(6));
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 + "<br>" + place.place_id);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

Deleting a marker from google maps with custom delete button

I am trying to delete a marker from google maps through a custom delete button. I have added the button and other information in the infowindow.
I have a function which deletes the marker from the map, the problem is when I press the delete button the function isnt called.
Here is my code:
function initMap() {
var jsonData = {$pointsArray};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
maxzoom: 15,
center: {
lat: 38,
lng: -77
}
});
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = jsonData.length; i < len; ++i) {
var point = jsonData[i];
var uniqueId = 1;
var markers = [];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(point.Lat, point.Lon),
map: map,
title: point.Title
});
bounds.extend(marker.position);
marker.id = uniqueId;
uniqueId++;
var contentString = '<div id="content">'+
'<h4 id="pointId" > ' + point.Title + '</h4>'+
'<h6 >City: ' + point.City + '</h6>'+
'<h6 >Latitude: ' + point.Lat+ '</h6>'+
'<h6 >Longitude: ' + point.Lon + '</h6>'+
'<h6 >Address: ' + point.Address + '</h6>'+
'<p data-placement="top" data-toggle="tooltip" title="Delete"><span class="glyphicon glyphicon-trash"></span></p>'
'</div>';
addInfoWindow(marker, contentString);
markers.push(marker);
}
function DeleteMarker(id) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id == id) {
markers[i].setMap(null);
markers.splice(i, 1);
return;
}
}
};
map.fitBounds(bounds);
}
Probably there is something wrong with the onclick attribute in the delete button, but I am not sure.
Help!
I think you have to use ' instead of " when you want to give marker.id as parameter because you used ' for the string and " for the attribute value. If you use " you just interrupt the attribute string for the onclick value.
In the rendered html, your function should look like this:
<p><a onclick="DeleteMarker('some id');"</a></p>
In order to achive that, put additional single quotes around the your id parameter:
onclick="deleteMarker('+"'"+ yourId +"'"+')

Driving Distance Calculation via Google Maps API

I want to calculate driving distance between given latitudes and longitudes. On my project I'm displaying markers on road. And what I want is to calculate distance between those markers not all of the routes. Can some one explain to me how can I calculate that distance?
I know I should work on DistanceMatrixService but I couldn't figure out how to work on it.
Where I put Markers:
var pointsArray = response.routes[0].overview_path;
for (var i = 0; i < pointsArray.length; i++) {
var marker = new google.maps.Marker ({
position:pointsArray[i],
draggable:false,
map:map,
flat:true
});
}
If the pointsArray comes from the directions service, you can do something like this:
var pointsArray = response.routes[0].overview_path;
for (var i = 0; i < pointsArray.length; i++) {
var marker = new google.maps.Marker({
position: pointsArray[i],
draggable: false,
map: map,
flat: true
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function (evt) {
var html = "marker #" + i + "<br />";
if (i != (markers.length - 1)) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i + 1) + "],\"click\");'>next</a>&nbspdist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i + 1].getPosition()).toFixed(2) + " meters<br />";
}
if (i !== 0) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i - 1) + "],\"click\");'>prev</a>&nbspdist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i - 1].getPosition()).toFixed(2) + " meters";
}
infowindow.setContent(html);
infowindow.open(map, marker);
}
})(marker, i))
}
Another option would be to get the distances out of the directions response.
code snippet:
var infowindow = new google.maps.InfoWindow();
var markers = [];
function initMap() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 37.4419,
lng: -122.1419
}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(new google.maps.LatLng(37.4419, -122.1419), new google.maps.LatLng(37.447597, -122.159582),
directionsService, directionsDisplay, map);
}
function calculateAndDisplayRoute(start, end, directionsService, directionsDisplay, map) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var pointsArray = response.routes[0].overview_path;
for (var i = 0; i < pointsArray.length; i++) {
var marker = new google.maps.Marker({
position: pointsArray[i],
draggable: false,
map: map,
flat: true
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function(evt) {
var html = "marker #" + i + "<br />";
if (i != (markers.length - 1)) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i + 1) + "],\"click\");'>next</a>&nbspdist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i + 1].getPosition()).toFixed(2) + " meters<br />";
}
if (i !== 0) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i - 1) + "],\"click\");'>prev</a>&nbspdist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i - 1].getPosition()).toFixed(2) + " meters";
}
infowindow.setContent(html);
infowindow.open(map, marker);
}
})(marker, i))
}
} else {
alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

Unsure why value becomes undefined in listener event for Google Maps [duplicate]

This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 7 years ago.
I am trying to get a string from an array of arrays. I want to get the first property [0] into an info window. I am able to use the second and third values to set the placement of markers and I am also able to console.log the first value.
The particular JavaScript code is here:
markers = [
["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964],
["7171 Woodmont Avenue", 38.980097, -77.093662],
["921 Wayne Avenue", 38.995740, -77.025652],
["801 Ellsworth Drive",38.997778, -77.025071]
];
infoWindow = new google.maps.InfoWindow()
for (var i = 0; i < markers.length; i++) {
console.log("markers: " + markers[i][0]);
position = new google.maps.LatLng(markers[i][1], markers[i][2]);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
console.log("markers 2: " + markers[i][0]);
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent("<div>Hello, World" + markers[i][0] + "</div>");
infoWindow.open(map, this);
});
};
When I console.log(markers[i][0]) it produces what I want. However, once it enters the addListener event, it loses it and I am not sure why.
Why does it become undefined?
Fiddle here.
HTML:
<h1 style="text-align: center;">Parking Garage Availability</h1>
<div id="map"></div>
<ul id="list"></ul>
<p id="GAR57"></p>
<p id="GAR31"></p>
<p id="GAR60"></p>
<p id="GAR61"></p>
CSS:
#map {
height: 300px;
width: 500px;
margin: 0 auto;
border: 1px solid black;
}
JavaScript:
var map;
var mapProp;
var marker;
var markers;
var url;
var myData;
var time;
var available;
var total;
var facility;
var position;
var infoWindow;
function initialize() {
mapProp = {
center: new google.maps.LatLng(38.994890, -77.063416),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapProp);
}
$(document).ready(function() {
initialize();
url = 'https://data.montgomerycountymd.gov/resource/qahs-fevu.json';
$.getJSON(url, function(data) {
myData = data;
for (i = 0; i < myData.length; i++) {
time = (myData[i].asofdatetime).slice(11);
available = myData[i].space_count;
total = myData[i].total_spaces;
facility = myData[i].facilitynumber;
if (facility === "GAR 57") {
facility = "4841 Bethesda Avenue (Elm Street)";
$('#GAR57').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
} else if (facility === "GAR 31") {
facility = "7171 Woodmont Avenue";
$('#GAR31').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
} else if (facility === "GAR 60") {
facility = "921 Wayne Avenue";
$('#GAR60').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
} else {
facility = "801 Ellsworth Drive";
$('#GAR61').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
}
}
});
//set markers
markers = [
["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964],
["7171 Woodmont Avenue", 38.980097, -77.093662],
["921 Wayne Avenue", 38.995740, -77.025652],
["801 Ellsworth Drive", 38.997778, -77.025071]
];
infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < markers.length; i++) {
console.log("markers: " + markers[i][0]);
position = new google.maps.LatLng(markers[i][1], markers[i][2]);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
console.log("markers 2: " + markers[i][0]);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent("<div>Hello, World" + markers[i][0] + "</div>");
infoWindow.open(map, this);
});
};
});
Markers[i][0] becomes undefined because it does not exist in the scope of the function within addListener i.e. you're not passing markers into the function.
Instead, you're passing in marker
for (var i = 0; i < markers.length; i++) {
console.log("markers: " + markers[i][0]);
position = new google.maps.LatLng(markers[i][1], markers[i][2]);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
console.log("markers 2: " + marker.title);
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent("<div>Hello, World " + marker.title + "</div>");
infoWindow.open(map, this);
});
};
This shows an example displaying the title when the marker is clicked. Which I'm assuming is what you wanted to achieve.

Google Maps: Google Places JS API: getDetails() not returning entire place details

I'm trying to show 2 locations on a map that when clicked display all the place details in their respective infowindows. I can only get a return of very limited place details to show, namely the address and that's about it. You can see here: http://www.intermountainvet.com/contact-0. I am console logging the place objects.
I know that there is a robust google place for this business, you can see here: https://www.google.com/maps/place/Intermountain+Pet+Hospital+%26+Lodge/#43.5906437,-116.4033528,15z/data=!4m6!1m3!3m2!1s0x0:0x2a5e055f442189ea!2sIntermountain+Pet+Hospital+%26+Lodge!3m1!1s0x0:0x2a5e055f442189ea
Why can't I access all of those place details to display in my infowindow?
Here is my code. (I have my api key and the libraries=places src in a script tag that I'm not showing here):
<script type="text/javascript">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 43.618928, lng: -116.274319},
zoom: 11
});
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
var locA = service.getDetails({
placeId: 'ChIJa_maRXxRrlQRSimVL1yUG8Q'
}, function(place, status) {
console.log(place);
console.log(status);
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<img src="' + place.icon + '" /><font style="color:#000;">' + place.name +
'<br />Rating: ' + place.rating + '<br />Vicinity: ' + place.vicinity + '</font>');
infowindow.open(map, this);
});
}
});
var locB = service.getDetails({
placeId: 'ChIJow1xfMRUrlQR6ewuO4NvrF0'
}, function(place, status) {
console.log(place);
console.log(status);
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<img src="' + place.icon + '" />font style="color:#000;">' + place.name +
'<br />Rating: ' + place.rating + '<br />Vicinity: ' + place.vicinity + '</font>');
infowindow.open(map, this);
});
}
});
}
Thanks for looking. I feel like this should be simple and I must be missing something minor.
You need to use the place id for the business (ChIJa_maRXxRrlQR6okhRF8FXio) not the address (ChIJa_maRXxRrlQRSimVL1yUG8Q)

Categories

Resources