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("Възникна проблем при намирането на местонахождението ви!");
}
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 });
<!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,
})
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>
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.
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>