Google Maps JS - Render only one leg from a route - javascript

I'm developing a JS webapp with Google Maps API.
I have to calculate the distance from A/D to B, B to C and C to A/D (please check the next image).
https://imgur.com/a/OiKJaXA
But, on the map, I have to render ONLY the second leg (legs[1], B to C). (check the image for more info)
https://imgur.com/a/zjQUu9h
What can I do to hide the first and last leg of my route? Of course, I could do another request, one for the map, one for the calculations, but I'm trying to be as efficient as possible.
My JS:
var mpos = "via Melzi deril 38 20154 Milano";
var madd = $("#i_madd_v").val() + ', ' + $("#i_madd_n").val() + ', ' + $("#i_madd_c").val();
var dadd = $("#i_dadd_v").val() + ', ' + $("#i_dadd_n").val() + ', ' + $("#i_dadd_c").val();
console.log(madd);
console.log(dadd);
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
var centro = new google.maps.LatLng(45.462861, 9.186453);
var mapOptions = {
zoom:11,
center: centro,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById('mappa'), mapOptions);
directionsRenderer.setMap(map);
calcRoute(directionsService, directionsRenderer);
}
function calcRoute(directionsService, directionsRenderer) {
var request = {
origin:mpos,
destination:mpos,
waypoints: [
{
location: madd,
stopover: true
},
{
location: dadd,
stopover: true
},
],
travelMode: 'DRIVING'
};
directionsService.route(request, function(response, status) {
if (status == 'OK') {
console.log(response);
console.log(status);
directionsRenderer.setDirections(response);
}
});
}
initMap();
});

If your route will always have 3 legs, and you always want to remove the 1st and last, you can modify the response from the directions service before passing it to the directions renderer:
directionsService.route(request, function(response, status) {
if (status == 'OK') {
response.routes[0].legs.splice(0,1); // remove 1st leg
response.routes[0].legs.splice(1,1); // remove last leg
directionsRenderer.setDirections(response);
} else alert("directions request failed:"+status);
});
proof of concept fiddle
code snippet:
var mpos = "via Melzi deril 38 20154 Milano";
var madd = "Monza, IT";
var dadd = "Segrate, IT";
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
var centro = new google.maps.LatLng(45.462861, 9.186453);
var mapOptions = {
zoom: 11,
center: centro,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById('mappa'), mapOptions);
directionsRenderer.setMap(map);
calcRoute(directionsService, directionsRenderer);
}
function calcRoute(directionsService, directionsRenderer) {
var request = {
origin: mpos,
destination: mpos,
waypoints: [{
location: madd,
stopover: true
},
{
location: dadd,
stopover: true
},
],
travelMode: 'DRIVING'
};
directionsService.route(request, function(response, status) {
if (status == 'OK') {
response.routes[0].legs.splice(0, 1);
response.routes[0].legs.splice(1, 1);
directionsRenderer.setDirections(response);
}
});
}
initMap();
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#mappa {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=&v=weekly"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="mappa"></div>
</body>
</html>

Related

Using geoPosition.js with colobox

I'm trying to create a colorbox link that ask the user for permission to detect his location, and if the user agree he gets a map with direction from his location.
Now I managed to make it work but not very well. In the first time when the user need to give permission the map loading perfectly, but in the second time when the permission already given the map not loading correctly.
my code:
function directionMap() {
var position;
jQuery('.direction-map').colorbox({
maxWidth: '100%',
maxHeight: '100%',
opacity: 0.5,
html: '<div id="map" style="width: 800px; height: 500px"></div>',
onLoad: function() {
var success = function(pos) {
var lat = pos.coords.latitude,
long = pos.coords.longitude,
coords = {lat: lat, lng: long};
var start = coords;
var target = {lat: 31.273257, lng: 34.797528};
var map = new google.maps.Map(document.getElementById('map'), {
center: start,
scrollwheel: false,
zoom: 7
});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// Set destination, origin and travel mode.
var request = {
destination: target,
origin: start,
travelMode: google.maps.TravelMode.DRIVING
};
// Pass the directions request to the directions service.
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
directionsDisplay.setDirections(response);
}
});
}
var error = function() {
alert('Can\'t find your location');
}
if (geoPosition.init()) {
geoPosition.getCurrentPosition(success, error, {
enableHighAccuracy:true,
timeout: 1000
});
}
return false;
},
});
}
My jsFiddle
I found the solution.
The problem was that the map should load after the colorbox completed, but just if the permission for location was given. so I wrote it with "onclick" handler and load the colorbox in the success variable.
this is the code:
function directionMap() {
document.getElementById('get_location').onclick = function() {
var success = function(pos) {
jQuery('.direction-map').colorbox({
maxWidth: '100%',
maxHeight: '100%',
opacity: 0.5,
html: '<div id="map" style="width: 800px; height: 500px"></div>',
open: true,
onComplete: function() {
var lat = pos.coords.latitude,
long = pos.coords.longitude,
coords = {lat: lat, lng: long};
var start = coords;
var target = {lat: 31.273257, lng: 34.797528};
var map = new google.maps.Map(document.getElementById('map'), {
center: start,
scrollwheel: false,
zoom: 7
});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// Set destination, origin and travel mode.
var request = {
destination: target,
origin: start,
travelMode: google.maps.TravelMode.DRIVING
};
// Pass the directions request to the directions service.
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
directionsDisplay.setDirections(response);
}
});
}
});
}
var error = function() {
alert('Can\'t find your location');
}
if (geoPosition.init()) {
geoPosition.getCurrentPosition(success, error, {
enableHighAccuracy:true,
timeout: 1000
});
}
return false;
}
}

Google Maps Directions using 1-2-3 instead of A-B-C

I'm using the Google Maps API on Google Maps.
The thing is that, It shows me several stations throughout the path, labeling them as A-B-C-D...Z, but I need to change it as 1-2-3-4-..99,
Here is my code;
directionsService.route({
origin: $( "#input-directions-start-point" ).val(),
destination: $( "#input-directions-end-point" ).val(),
waypoints: waypts, //other duration points
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
console.log(response);
} else {
vts.alertDialog( window.localization.error,
window.localization.error_direction_calculate + ": " + status,
BootstrapDialog.TYPE_DANGER);
}
});
Here is the Screen Shot;
Thanks in Advance
google.maps.DirectionsRendererOptions has property suppressMarkers which when you set to true, will only render the path but not markers.
You can then render the markers yourself using for example google.maps.Marker, which has label attribute using which you can specify the label inside the marker, which can be for example a number (You can also create your own very custom marker by extending google.maps.OverlayView class, or use RichMarker library). The position of the markers on route can be parsed from response object of directionsService.
More in docs.
Working example:
function init(){
directionsService = new google.maps.DirectionsService();
var pos = new google.maps.LatLng(41.218624, -73.748358);
var myOptions = {
zoom: 15,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true});
directionsService.route({
origin: "New York",
destination: "Chicago",
waypoints: [{location:"Philadelphia"}, {location:"Boston"}], //other duration points
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var my_route = response.routes[0];
for (var i = 0; i < my_route.legs.length; i++) {
var marker = new google.maps.Marker({
position: my_route.legs[i].start_location,
label: ""+(i+1),
map: map
});
}
var marker = new google.maps.Marker({
position: my_route.legs[i-1].end_location,
label: ""+(i+1),
map: map
});
} else {
vts.alertDialog( window.localization.error,
window.localization.error_direction_calculate + ": " + status,
BootstrapDialog.TYPE_DANGER);
}
});
}
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("maps", "3",{other_params:"sensor=false"});
</script>
<body style="margin:0px; padding:0px;" onload="init()">
<div id="map" style="height:400px; width:500px;"></div>
</body>

How do I get Google Maps Directions API to choose the correct Airport?

When I ask google for directions, both "MMU" and "MMU Airport" work fine, but when I use the API it keeps going to MLU airport... what gives?
Code:
var directionService = new google.maps.DirectionsService;
var geocoder = new google.maps.Geocoder;
directionService.route({
origin: $('#selAirport').val() + ' Airport',
destination: $('#selZIPZone').val(),
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
console.log(response, status);
...
dev-tools photo showing it received "MMU Airport" as the origin, but set the Start Address to MLU Airport instead
That looks like a data problem. The directions service/geocoder recognize Morristown Municipal Airport, but not MMU. I reported that through the Google Maps "report an error" (lower right hand corner of the map), not sure if it will be accepted.
code snippet:
var geocoder;
var map;
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
});
var directionService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionService.route({
origin: 'Morristown Airport',
destination: "Florham Park , NJ",
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
console.log(response);
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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Taking into account your last comment it looks like you have an autocomplete of places library. In this case you can retrieve the place ID from the autocomplete element and pass it to directions service. This way you will be sure that directions service is working with an exact choice of the user.
Please look at this example and use autocomplete to search your route:
http://jsbin.com/xuyisem/edit?html,output
code snippet:
var directionsDisplay;
var directionsService;
var map;
var placeId1, placeId2;
function initialize() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true
});
var mapOptions = {
zoom:10,
center: new google.maps.LatLng(32.5101466,-92.0436835)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
var inputFrom = document.getElementById('from');
var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, {});
autocompleteFrom.bindTo('bounds', map);
autocompleteFrom.addListener('place_changed', function() {
var place = autocompleteFrom.getPlace();
placeId1 = place.place_id;
});
var inputTo = document.getElementById('to');
var autocompleteTo = new google.maps.places.Autocomplete(inputTo, {});
autocompleteTo.bindTo('bounds', map);
autocompleteTo.addListener('place_changed', function() {
var place = autocompleteTo.getPlace();
placeId2 = place.place_id;
});
}
function calcRoute() {
if (!placeId1) {
alert("Please select origin");
return;
}
if (!placeId2) {
alert("Please select destination");
return;
}
var start = {
placeId: placeId1
};
var end = {
placeId: placeId2
};
var request = {
origin: start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: false
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<input type="text" name="from" id="from" placeholder="Select origin" />
<input type="text" name="to" id="to" placeholder="Select destination" />
<input type="button" name="calcroute" value="Get route" onclick="calcRoute();return false;" />
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initialize"></script>

Google Map doesn't loads properly in ligh box pop up

I have two textbox in which we can enter locations & on button click route between two points shows in the map. Problem is on page it shows properly but when I use lighbox popup then map only shows grey color like below image. For pop up box I have used asp.net control modalpopupextender.
JS Code.
<script type="text/javascript">
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
debugger;
var mumbai = new google.maps.LatLng(18.9750, 72.8258);
var mapOptions = {
zoom: 7,
center: mumbai
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var distance2 = response.rows[0].elements[0].distance.text; /*used for ID firstNumber*/
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
var firstNumber = document.getElementById("firstNumber");
var dvDuration = document.getElementById("dvDuration");
var dvDurationC = document.getElementById("dvDurationC")
dvDistance.innerHTML = "";
dvDistance.value = parseFloat(distance);
firstNumber.innerHTML = distance2 /*used for ID firstNumber*/
dvDuration.innerHTML = duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
Try making these two changes:
Remove the display property and set visibility: hidden on #map.
Move #map to a place where the space it inhabits won’t be noticed. Right before is probably a good choice.
Refer to this tutorial.

how to invoke javascript function with more than one argument from silverlight project?

i had some trouvle with invoking a javascript function with more than one argument from a html page that is what i am doing :
wbNavigator.Navigate(new Uri("http://localhost:56433/route.html" ,UriKind.Absolute) );
object results= wbNavigator.InvokeScript("calculer", new string[] {"3.072526", "36.766942", "3.042526", "36.766942"});
but when invoking nothing's hapening .Am i missing something ?
that is my javascript Code :
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
function calcluer(lon_A, lat_A, lon_B, lat_B) {
var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);
var salle2 = new google.maps.LatLng(lat_A, lon_A);
var salle3 = new google.maps.LatLng(lat_B, lon_B);
var request = {
origin: salle2,
destination: salle3,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the distance:
document.getElementById('distance').innerHTML +=
response.routes[0].legs[0].distance.value + " meters";
// Display the duration:
document.getElementById('duration').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
directionsDisplay.setDirections(response);
}
});
}
</script>
Just use:-
object results= wbNavigator.InvokeScript("calculer", "3.072526", "36.766942", "3.042526", "36.766942");
Note that doing this immediately after navigate may not have the desired effect. You should perhaps move this code to the LoadCompleted event of the WebBrowser.

Categories

Resources