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>
Related
Below is my code for delivery person tracking. I'm using Maps Javascript API v3 in Ionic-angular food delivery application. I need user to see delivery boy position in realtime. I have succeeded in drawing a polyline, placing delivery boy, user and restaurant markers. The delivery boy marker is moving on location change. But i need to redraw polyline everytime when delivery boy moves. How to do that? Click the link for full code
https://pastebin.com/We8BQd7H
directionsDisplay.setMap(map);
// directionsDisplay.setOptions({ suppressMarkers: true });
directionsDisplay.setOptions({
polylineOptions: {
strokeWeight: 4,
strokeOpacity: 1,
strokeColor: "#000000",
},
suppressMarkers: true,
});
var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA],
travelMode: "DRIVING",
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
},
function (response, status) {
console.log('distance matrix response', response);
if (status !== "OK") {
alert("Error was: " + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById("output");
// outputDiv.innerHTML = '';
// deleteMarkers(markersArray);
var showGeocodedAddressOnMap = function (asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function (results, status) {
if (status === "OK") {
map.fitBounds(bounds.extend(results[0].geometry.location));
// markersArray.push(new google.maps.Marker({
// map: map,
// position: results[0].geometry.location,
// icon: icon
// }));
} else {
alert("Geocode was not successful due to: " + status);
}
};
};
directionsService.route(
{
origin: origin1,
destination: destinationA,
travelMode: "DRIVING",
},
function (response, status) {
console.log('direction response', response);
if (status === "OK") {
directionsDisplay.setDirections(response);
} else {
window.alert("Directions request failed due to " + status);
}
}
);
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode(
{ address: originList[i] },
showGeocodedAddressOnMap(false)
);
for (var j = 0; j < results.length; j++) {
geocoder.geocode(
{ address: destinationList[j] },
showGeocodedAddressOnMap(true)
);
}
}
}
}
According to the documentation If you want to redraw you're polyline, store it in a variable and use the setmap(null) method.
You can write an update function to remove you're old polyline, update his path, and redraw it. The code can look like this :
let map;
let directionsDisplay;
// assuming you have almost the first two point of the line to draw it
let pathCoordinate = [
{ lat: 37.772, lng: -122.214 },
{ lat: 21.291, lng: -157.821 },
];
let polylineShape = {
strokeWeight: 4,
strokeOpacity: 1,
strokeColor: "#000000",
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
//... you're configuration
});
}
function updatePath(newCoordinate) {
// remove old polyline
directionsDisplay.setMap(null);
// update coordinate
pathCoordinate.push(newCoordinate);
// set the new polyline
directionsDisplay = new google.maps.Polyline({...polylineShape, ...{path:pathCoordinate});
directionsDisplay.setMap(map);
}
//
initmap();
directionsDisplay = new google.maps.Polyline({...polylineShape, ...{path:pathCoordinate});
directionsDisplay.setMap(map);
// then call updatePath() every time you need to update
updatePath({ lat: -18.142, lng: 178.431 });
I would like to create a link that open a new google map tab with route from navigator.geolocation.getCurrentPosition to a specific placeId.
If there is geolocation a problem then, open a new tab without origin completed
Here is what I try:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
latitude: 48.925606,
longitude: 2.327621,
};
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
$('.js-ItinaryFromI').on('click', () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
}, () => {
// The problem seems to come from this line :
window.open(`https://www.google.com/maps/dir/origin=pos&destination=place_id:${options.placeId}&travelmode=driving`, '_blank');
});
} else {
// And this line
window.open(`https://www.google.com/maps/dir//place_id${options.placeId}&travelmode=driving`, '_blank');
}
});
Any idea please ?
You should use Google Maps Directions API if you wanted to calculate directions between location. You can search for directions for several modes of transportation, including transit, driving, walking, or cycling.
These parameters (origin, destination, travel_mode) are used in Google Maps Directions API and probably won't work well using Google Maps.
I also noticed in the code you provided that certain variables were not properly concatenated into the request. Hence, your request would not provide accurate results.
Here's a sample of valid request:
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=YOUR_API_KEY', '_blank');
Don't forget to include your API key in each request.
I modified your code a bit. You can check it below:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
//placeId: 'ChIJ51Ic7BXIlzMRK2WH8qoM6Ek',
latitude: 48.925606,
longitude: 2.327621,
};
function initMap() {
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
document.getElementById('js-ItinaryFromI').addEventListener('click', () => {
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=[API-KEY]', '_blank');
});
});
} else {
alert('Geolocation not found!');
}
}
html,body,#Map {
width:100%;
height:100%;
}
<button id="js-ItinaryFromI">Click Me</button>
<div id="Map" ></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap&libraries=places">
</script>
You can try this using JSBin. For some reason it doesn't work here in Stackoverflow's code snippet. I don't know why.
Good luck and happy coding!
I am trying to add cluster marker to google maps in angularjs.
I have already included the js file (https://github.com/googlemaps/js-marker-clusterer/blob/gh-pages/src/markerclusterer.js) and the images (https://github.com/googlemaps/js-marker-clusterer/tree/gh-pages/images).
However the cluster still not appears.
This is my code:
html:
<section id="GoogleMaps" ng-controller="MapsController">
<div class="container">
<div>
<div id="map_canvas"></div>
</div>
</div>
</section>
controller:
.controller('MapsController', ['$scope', '$http', function ($scope, $http) {
$scope.loadData = function () {
var url = 'data/LatLng.json';
return $http.get(url).then(function (response) {
return response.data;
});
};
$scope.initMap = function (data) {
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(48.209500, 16.370691),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
data.forEach(function (item) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.LAT, item.LON),
animation: google.maps.Animation.Bounce,
map: map
});
var options = {
imagePath: 'images/m'
};
var markerCluster = new MarkerClusterer(map, marker, options);
});
};
$scope.loadData()
.then($scope.initMap);
}])
scripts:
addTag('script', { src: 'http://maps.googleapis.com/maps/api/js' }, sync);
addTag('script', { src: 'assets/js/markerclusterer.js' }, sync);
Any ideas how to add it?
Thank You.
Initialise the MarkerClusterer as following way.
$scope.initMap = function (data) {
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(48.209500, 16.370691),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var markerArray = [];
data.forEach(function (item) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.LAT, item.LON),
animation: google.maps.Animation.Bounce,
map: map
});
markerArray.push(marker);
});
var options = {
imagePath: 'images/m'
};
var markerCluster = new MarkerClusterer(map, markerArray, options);
};
When you initialize it in forEach loop, it creates new object of it.
I am trying to use the geolocations API with the Directions service but I get:
var UserLoc;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat=position.coords.latitude;
var lng=position.coords.longitude;
console.log(lat);
console.log(lng);
UserLoc = new google.maps.LatLng(lat,lng);
var NewMarker = new google.maps.Marker({
position: UserLoc,
draggable: false,
animation: google.maps.Animation.DROP,
map: SEVTmap
});
}
);
}
else {
alert ( "Възникна проблем при намирането на местонахождението ви!" );
}
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(SEVTmap);
var request = {
origin: UserLoc,
destination: Destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
Error : InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object; and not an Object
The marker is created;
The geolocation service is asynchronous, you have to use the result in its callback function when/where it is available
var UserLoc;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log(lat);
console.log(lng);
UserLoc = new google.maps.LatLng(lat, lng);
var NewMarker = new google.maps.Marker({
position: UserLoc,
draggable: false,
animation: google.maps.Animation.DROP,
map: SEVTmap
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: SEVTmap
});
directionsDisplay.setMap(SEVTmap);
var request = {
origin: UserLoc,
destination: Destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}, function (PositionError) {alert("geolocation error:"+PositionError.code+" msg="+PositionError.message);});
} else {
alert("Възникна проблем при намирането на местонахождението ви!");
}
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>