direction service failed due to - javascript

<!DOCTYPE html>
<html>
<head>
<title>Google Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<style>
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function initMap() {
const directionsRenderer = new google.maps.DirectionsRenderer();
const directionsService = new google.maps.DirectionsService();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 14,
center: { lat: 20.5937, lng: 78.9629 },
});
directionsRenderer.setMap(map);
calculateAndDisplayRoute(directionsService, directionsRenderer);
}
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
const success = (position) => {
var la = position.coords.latitude;
var lo = position.coords.longitude;
var latt = document.getElementById('latt').value;
var lngg = document.getElementById('lngg').value;
console.log(latt);
console.log(lngg);
directionsService.route({
origin: { lat: la, lng: lo},
destination: { lat: latt, lng: lngg },
travelMode: google.maps.TravelMode.DRIVING,
})
.then((response) => {
directionsRenderer.setDirections(response);
})
.catch((e) => window.alert("Directions request failed due to " + status));
}
const error = (error) => {
console.log(error)
}
navigator.geolocation.getCurrentPosition(success, error);
}
</script>
</head>
<body >
<div id="map" ></div>
<input type="hidden" id="latt" value="{{lat}}">
<input type="hidden" id="lngg" value="{{lng}}">
<script src="https://maps.googleapis.com/maps/api/js?key=[API KEY HERE ] & c allback = initMap
&libraries=&v=weekly" async></script>
</body>
</html>
In destination when i give latitude and longitude then this code perfectly works but when i give latitude and logitude using variable then it shows error Directions request failed due to and cannot return any status i am using django framework for my project and fetching latitude and longitude from database.

Need to convert latt and lngg to a number
example:
var latt = document.getElementById('latt').value;
var lngg = document.getElementById('lngg').value;
var a = Number(latt);
var b = Number(lngg);
directionsService.route({
origin: { lat: la, lng: lo},
destination: { lat: a, lng: b },
travelMode: google.maps.TravelMode.DRIVING,
})

Related

Google Maps API Finding Details

I am trying to use the google maps details about a location to display in an info window from a marker. I am creating a marker and want to get the address of that marker so that I can store it in a database. I am able to get the title of the marker but I do not know how to get the full address. This is my code:
<script>
let pos;
let map;
let bounds;
let infoWindow;
let currentInfoWindow;
let service;
let infoPane;
function initMap() {
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow;
currentInfoWindow = infoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
bounds.extend(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearbyPlaces(pos);
}, () => {
handleLocationError(true, infoWindow);
});
} else {
handleLocationError(false, infoWindow);
}
}
function handleLocationError(browserHasGeolocation, infoWindow) {
pos = { lat: -33.856, lng: 151.215 };
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Geolocation permissions denied. Using default location.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
currentInfoWindow = infoWindow;
getNearbyPlaces(pos);
}
function getNearbyPlaces(position) {
let request = {
location: position,
rankBy: google.maps.places.RankBy.DISTANCE,
keyword: 'basketball courts'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, nearbyCallback);
}
function nearbyCallback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarkers(results);
}
}
function createMarkers(places) {
places.forEach(place => {
let marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title: place.name
});
marker.addListener("click", () => {
map.setZoom(16);
map.setCenter(marker.getPosition());
});
bounds.extend(place.geometry.location);
});
map.fitBounds(bounds);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>
I am unfamiliar with javascript so I am not sure how exactly to format it. If it shows up in the infowindow I can work on it myself from there but if anyone has suggestions on how to show it there I would appreciate it.
To be fair you have done most of the work but if it is simply a case of taking the results from the nearbyPlaces search and adding to an infowindow then perhaps you can find use in the following. The work is done in the createMarkers function
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Google Maps: </title>
<style>
#map{
width:800px;
height:600px;
float:none;
margin:auto;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
let pos;
let map;
let bounds;
let infoWindow;
let currentInfoWindow;
let service;
let infoPane;
function initMap() {
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow;
currentInfoWindow = infoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
bounds.extend(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearbyPlaces( pos );
}, () => {
handleLocationError(true, infoWindow);
});
} else {
handleLocationError(false, infoWindow);
}
}
function handleLocationError(browserHasGeolocation, infoWindow) {
pos = { lat: -33.856, lng: 151.215 };
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Geolocation permissions denied. Using default location.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
currentInfoWindow = infoWindow;
getNearbyPlaces(pos);
}
function getNearbyPlaces(position) {
let request = {
location: position,
rankBy: google.maps.places.RankBy.DISTANCE,
keyword: 'basketball courts'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, nearbyCallback);
}
function nearbyCallback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarkers(results);
}
}
function createMarkers(places) {
places.forEach(place => {
console.log(place)
let marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title:place.name,
/* assign the response data as a property of the marker */
content:place
});
/*
for convenience a regular anonymous function is better here
as it allws us to use `this` to refer to the marker itself
within the body of the function.
*/
marker.addListener("click", function(e){
map.setZoom(16);
map.setCenter( marker.getPosition() );
/*
Iterate through ALL properties ( or just some ) of the `this.contents`
property and set as the content for the infowindow
*/
infoWindow.setContent( Object.keys(this.content).map(k=>{
return [k,this.content[k] ].join('=')
}).join( String.fromCharCode(10) ) );
/* open the infowindow */
infoWindow.setPosition(e.latLng)
infoWindow.open(map,this);
});
bounds.extend(place.geometry.location);
});
map.fitBounds(bounds);
}
</script>
<script async defer src="//maps.googleapis.com/maps/api/js?key=<APIKEY>&libraries=places&callback=initMap">
</script>
</body>
</html>
The data returned is JSON and has a structure like this for each individual result. The location data contained therein will bear no resemblance to that found for others running this self same script but show suffice.
{
"business_status" : "OPERATIONAL",
"geometry" : {
"location" : {
"lat" : 52.7525688,
"lng" : 0.4036446
},
"viewport" : {
"northeast" : {
"lat" : 52.75354047989272,
"lng" : 0.4048724298927222
},
"southwest" : {
"lat" : 52.75084082010728,
"lng" : 0.4021727701072778
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_business-71.png",
"icon_background_color" : "#7B9EB0",
"icon_mask_base_uri" : "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet",
"name" : "Multi-Use Games Area",
"place_id" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
"plus_code" : {
"compound_code" : "QC33+2F King's Lynn",
"global_code" : "9F42QC33+2F"
},
"rating" : 0,
"reference" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
"scope" : "GOOGLE",
"types" : [ "point_of_interest", "establishment" ],
"user_ratings_total" : 0,
"vicinity" : "The Walks, nr, South St, King's Lynn"
}
Within the marker click callback function, where previously there is this:
infoWindow.setContent( Object.keys(this.content).map(k=>{
return [k,this.content[k] ].join('=')
}).join( String.fromCharCode(10) ) );
We can build up a string of whatever items you wish to use:
infoWindow.setContent( this.content.name ); // simply display the name
or
infoWindow.setContent(
`<h1>${this.content.name}</h1>
<p>${this.content.vicinity}</p>
<ul>
<li>Lat: ${this.content.geometry.location.lat()}</li>
<li>Lng: ${this.content.geometry.location.lng()}</li>
</ul>
<img src="${this.content.icon}" />`
); // show some HTML content

Difficulty with Google Maps API

I am trying to create a simple program that takes in specifically two specifically placed destinations and shows the directions in between them. For whatever reason, I just cannot get the directions to show up.
<script>
var directionsService = new google.maps.directionsService();
var directionsDisplay = new google.maps.directionsRenderer();
var new_york = {lat: 40.7128, lng: -74.0060};
var los_angeles = {lat: 34.0522, lng: -118.2437};
function initMap() {
var mapMarkers = [];
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
);
var marker1 = new google.maps.Marker({
position: new_york,
map: map,
title: 'Home'
});
var marker2 = new google.maps.Marker({
position: los_angeles,
map: map,
title: 'School'
});
}
calculateAndDisplayRoute: function(directionsService, directionsDisplay, new_york, los_angeles) {
directionsService.route({
origin: new_york,
destination: los_angeles,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDmA98U4We-2IAaHbxa354v_C91IktiSKM3&callback=calculateAndDisplayRoute"></script>
I think there are a few problems with your code, first you need to be aware that the google maps library needs to be loaded before you can create new instances of DirectionsService and DirectionsRenderer, which btw should be in CamelCase:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
Since you are not loading the maps library asynchronously you can place the script at the top of your page and just drop the callback argument. I've made a few changes to your code, please check it out below (you need to add your api key):
var new_york = {lat: 40.7128, lng: -74.0060};
var los_angeles = {lat: 34.0522, lng: -118.2437};
function initMap() {
var mapMarkers = [];
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
);
var marker1 = new google.maps.Marker({
position: new_york,
map: map,
title: 'Home'
});
var marker2 = new google.maps.Marker({
position: los_angeles,
map: map,
title: 'School'
});
}
function calculateAndDisplayRoute() {
initMap();
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var route = {
origin: new_york,
destination: los_angeles,
travelMode: 'DRIVING'
};
directionsService.route(route, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
calculateAndDisplayRoute();
<script src="https://maps.googleapis.com/maps/api/js?key=???"></script>
<div id="map" style="width: 100%; height: 500px;"></div>

let user get direction to specific location from his location in my website

I tried to combine this links with each other
"https://developers.google.com/maps/documentation/javascript/geolocation"
and
"https://developers.google.com/maps/documentation/javascript/examples/directions-panel"
but there is a problem with combining together by pushing user current location to a inner html of "div" and then get it back to push it into start of direction path
<script>
var infoWindow;
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: { lat: 30.0879217, lng: 31.3439407 }
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById("position1").innerHTML=position.coords.latitude;
document.getElementById("position2").innerHTML=position.coords.longitude;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
document.getElementById('mode').addEventListener('change', function () {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
var x=document.getElementById("position1").innerHTML;
var y=document.getElementById("position2").innerHTML;
directionsService.route({
origin: { lat: 30.0879217, lng: 31.3439407 }, // Haight.
destination: { lat: Number(x), lng: Number(y) }, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
}, function (response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCb0QRzb5LcbAkUbRH3kRDv4WNVDRMBeq4&callback=initMap">
</script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
</style>
</head>
<body>
<div id="position1" ></div>
<div id="position2"></div>
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
<div id="map"></div>
You can try something like this:
<script>
var infoWindow;
function initMap() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById("position1").innerHTML=position.coords.latitude;
document.getElementById("position2").innerHTML=position.coords.longitude;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: { lat: 30.0879217, lng: 31.3439407 }
});
infoWindow = new google.maps.InfoWindow;
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
document.getElementById('mode').addEventListener('change', function () {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
var x=document.getElementById("position1").innerHTML;
var y=document.getElementById("position2").innerHTML;
directionsService.route({
origin: { lat: 30.0879217, lng: 31.3439407 }, // Haight.
destination: { lat: Number(x), lng: Number(y) }, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
}, function (response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCb0QRzb5LcbAkUbRH3kRDv4WNVDRMBeq4&callback=initMap">
</script>
Your code crash because you tried to read your position in the calculateAndDisplayRoute before the browser calls your callback where you initialize the lat and long HTML's objects.
Tell me if you have some questions or comments.

Meteor implementing Google Maps and Google Places

I'm attempting to implement a Google Map on my Meteor app that will get the user's location and then will find places that serve food near the user. I began by implementing the example
given by Google, and it worked fine when I did it that way; however I'm trying to implement it properly by adding it to the actual Javascript file and it is now giving me a "Google is undefined" error.
menuList = new Mongo.Collection('items');
if (Meteor.isClient) {
var pls;
var map;
var infowindow;
Meteor.startup(function () {
//get user location and return location in console
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
pls = {lat: crd.latitude, lng: crd.longitude};
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
})
Meteor.methods({
callback: function (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
},
createMarker: function (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);
});
}
})
Template.searchIt.helpers({
'initMap': function () {
console.log("HERE");
//Dummy values I placed for StackOverflow
var pyrmont = {lat: -33.234, lng: 95.343};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
types: ['food']
}, callback);
}
})
}
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACgaDFJrh2pMm-bSta1S40wpKDDSpXO2M
&signed_in=true&libraries=places" async defer></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
{{>searchIt}}
</body>
<template name="searchIt">
{{initMap}}
</template>
You should try the dburles:google-maps package.
Here is an example written by its author: http://meteorcapture.com/how-to-create-a-reactive-google-map/
Have fun!
i had to place the code you have above inside of a GoogleMaps.ready('map', callback) block. or inside of an if (GoogleMaps.loaded()) {} block...
for instance.. this works just fine:
caveat: i'm using the radarSearch, but the concept is the same.
Template.galleryCard.onRendered(function() {
GoogleMaps.ready('minimap', function(map) {
const params = {
map: map,
name: 'The Spice Suite',
loc: {lat: 38.9738619, lng: -77.01829699999999},
};
const service = new google.maps.places.PlacesService(params.map.instance);
let request2 = {
//name & location & radius (meters).
name: params.name,
location: params.loc,
radius: 100,
};
let callback = function(results,status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(results[0]);
return results[0].place_id;
} else {
console.log(status);
}
};
service.radarSearch(request2,callback);
});
});

Pass Place ID location to destination in Google Maps API

I'm trying to figure out how to pass the geometry location of a Google Places location to the directions service request destination dynamically. If I use
service.getDetails({
placeId: 'ChIJy_YmBMEMIocRZF8r5wPFMYU'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: 'img/pillicon.jpg'
});
}
to get the position how can I then pass that to my request like so
var request = {
origin: currentLoc,
destination: place.geometry.location, //not sure about this
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
I've tried returning the place.geometry.location and then calling it, and converting it to a string, but I still can't access it. Thanks I'm new to javascript
Simplest way: pass the placeId directly into the DirectionsRequest
proof of concept fiddle
code snippet:
var geocoder;
var map;
var service;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var curLoc = new google.maps.LatLng(35.0853336, -106.6055534);
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(curLoc, {
placeId: 'ChIJy_YmBMEMIocRZF8r5wPFMYU'
}, directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(start, end, directionsService, directionsDisplay) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
Most likely your issue is that the PlacesService is asynchronous, you need to use the result returned inside its callback routine.
proof of concept fiddle
code snippet:
var geocoder;
var map;
var service;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var curLoc = new google.maps.LatLng(35.0853336, -106.6055534);
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJy_YmBMEMIocRZF8r5wPFMYU'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: 'http://maps.google.com/mapfiles/ms/micons/blue.png'
});
map.setCenter(marker.getPosition());
calculateAndDisplayRoute(curLoc, marker.getPosition(), directionsService, directionsDisplay);
}
});
}
function calculateAndDisplayRoute(start, end, directionsService, directionsDisplay) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>

Categories