I wanted to make it so onl oad my google maps shows a route from wherever I am (through geolocation) to the destination. I have a snippet where it sets a route between 2 points 1 snippet where the function grabs my current coordinates.
Issue: I don't understand how I can merge these together to get the desired result.
Here's the code I'm working with. Any help is appreciated. (tho in these demos getting cordinates won't work, it does work in my vsc.
//To get user coordinates
var myLocation = document.getElementById("XYZ");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
myLocation.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
myLocation.innerHTML = "Latitude: " position.coords.latitude
"<br>Longitude: " position.coords.longitude;
}
// Google Maps
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initMap() {
directionsDisplay = new google.maps.DirectionsRenderer();
var porto = new google.maps.LatLng(41.1579416, -8.6257744);
var mapOptions = {
zoom: 10,
center: porto}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
calcRoute(map);
}
function calcRoute(map) {
var start = new google.maps.LatLng(41.1579416, -8.327744);
var end = new google.maps.LatLng(41.1579416, -8.6257744);//linha = localização no porto
var startMark = new google.maps.Marker({
position: start,
map: map,
title: "start"
});
var endMark = new google.maps.Marker({
position: end,
map: map,
title: "end"
});
var request = {
origin: start,
destination: end,
travelMode: 'DRIVING'
};
directionsService.route(request, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
alert("directions request failed, status=" status)
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key="></script>
<div id="map"style="height:200px"></div>
<button id="XYZ" onclick="getLocation()">gib coordinates</button>
CodePudding user response:
The geolocation service is asynchronous. Call the calcRoute
function inside the geolocation callback function, passing in the position returned once it returns the response:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, errorHandler);
} else {
myLocation.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
myLocation.innerHTML = "Latitude: " position.coords.latitude
"<br>Longitude: " position.coords.longitude;
var currentPosition = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
calcRoute(map, currentPosition);
}
and for robustness, call it with a default start location (or error message) in the error handler.
function errorHandler(err) {
console.warn('ERROR(' err.code '): ' err.message);
var defaultPosition = new google.maps.LatLng(41.1579416, -8.327744);
calcRoute(map, defaultPosition);
};
live example, with fix for locations in USA
code snippet:
//To get user coordinates
var myLocation = document.getElementById("XYZ");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, errorHandler);
} else {
myLocation.innerHTML = "Geolocation is not supported by this browser.";
}
}
function errorHandler(err) {
console.warn('ERROR(' err.code '): ' err.message);
var defaultPosition = new google.maps.LatLng(41.1579416, -8.327744);
calcRoute(map, defaultPosition);
};
function showPosition(position) {
myLocation.innerHTML = "Latitude: " position.coords.latitude
"<br>Longitude: " position.coords.longitude;
var currentPosition = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
calcRoute(map, currentPosition);
}
// Google Maps
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initMap() {
directionsDisplay = new google.maps.DirectionsRenderer();
var porto = new google.maps.LatLng(41.1579416, -8.6257744);
var mapOptions = {
zoom: 10,
center: porto
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute(map, currentPosition) {
var end = new google.maps.LatLng(41.1579416, -8.6257744); //linha = localização no porto
var startMark = new google.maps.Marker({
position: currentPosition,
map: map,
title: "start"
});
var endMark = new google.maps.Marker({
position: end,
map: map,
title: "end"
});
var request = {
origin: currentPosition,
destination: end,
travelMode: 'DRIVING'
};
directionsService.route(request, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
alert("directions request failed, status=" status)
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
#map {
height: 90%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
<button id="XYZ" onclick="getLocation()">get coordinates</button>