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

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>

Related

How to set the marker visible on google map draggable direcion

I would like to make a Directions on google map , and there is my code.
In the code , there are four Markers on it.
I want that I can decide which markers I want to hide.
How to set the marker visible on google map draggable direcion?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 22.65, lng: 120.30}
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('22.650927, 120.328185' , '22.656672, 120.307596', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: [{location:new google.maps.LatLng(22.651682, 120.324307)},{location:new google.maps.LatLng(22.655168, 120.320009)}],
travelMode: google.maps.TravelMode.DRIVING,
avoidTolls: true
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
The picture shows the directions look like.
If you are using jQuery, try getting the markers like this:
var markers = $('#map_canvas').gmap('get','markers');

suppressMarkers and draggable for DirectionsRendererOptions Google Maps API

I'm using Google Maps API to create a direction with the given points.
I need to order the points as 1,2,3...99 (It's done).
Also the points must be draggable.
But when I make the points draggable, the direction does not refresh itself, point's locations change but not the direction,
Here is the sample code(taken from the --> Google Maps Directions using 1-2-3 instead of A-B-C);
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("maps", "3",{other_params:"sensor=false"});
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,draggable: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,
draggable:true,
label: ""+(i+1),
map: map
});
}
var marker = new google.maps.Marker({
position: my_route.legs[i-1].end_location,
draggable:true,
label: ""+(i+1),
map: map
});
} else {
vts.alertDialog( window.localization.error,
window.localization.error_direction_calculate + ": " + status,
BootstrapDialog.TYPE_DANGER);
}
});
}
</script>
<body style="margin:0px; padding:0px;" onload="init()">
<div id="map" style="height:400px; width:500px;"></div>
</body>
Here is the screen shots;
Here is the problem;
The thing is that, I have to do it with both markers and draggable properties.
Thanks in advance
Just recalculate the route every time a marker is dragged. Listen for the dragend event and calculate route again and then render it on map, again with suppressing markers. Careful though, if you drag a marker to some position where route cannot be calculated (e.g. over sea, or some mountains, etc.) you would get error when re-calculating the route.
Working example:
function init(){
var markers = [];
var 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++) {
addDraggableDirectionsMarker(my_route.legs[i].start_location, i+1, map, markers, directionsService, directionsDisplay);
}
addDraggableDirectionsMarker(my_route.legs[i-1].end_location, i+1, map, markers, directionsService, directionsDisplay);
} else {
vts.alertDialog( window.localization.error,
window.localization.error_direction_calculate + ": " + status,
BootstrapDialog.TYPE_DANGER);
}
});
}
function addDraggableDirectionsMarker(position, label, map, markers, directionsService, directionsDisplay){
var marker = new google.maps.Marker({
position: position,
label: "" + label,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'click', function(){
//do whatever you want on marker click
});
google.maps.event.addListener(marker, 'dragend', function(){
if(markers.length < 2) return;
var waypoints = [];
for(var i = 1; i < markers.length - 1; i++) waypoints.push({location:markers[i].getPosition()});
directionsService.route({
origin: markers[0].getPosition(),
destination: markers[markers.length-1].getPosition(),
waypoints: waypoints,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
//uncomment following code if you want the markers you dragged to snap to the route, closest to the point where you dragged the marker
/*var my_route = response.routes[0];
for (var i = 0; i < my_route.legs.length; i++) {
markers[i].setPosition(my_route.legs[i].start_location);
}
markers[i].setPosition(my_route.legs[i-1].end_location);*/
} else {
vts.alertDialog( window.localization.error,
window.localization.error_direction_calculate + ": " + status,
BootstrapDialog.TYPE_DANGER);
}
});
});
markers.push(marker);
}
<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>

Google maps API DirectionsService between lat and long and GeolocationMarker

I am trying to get the directions services working on google maps api v3.
It is a webapp for smartphones where the user can get directions from where they are (GeolocationMarker) to a static (hardcoded) location defined by a lat and long.
The map centres on the hard coded lat and long, and then I have an icon (gps.png) that onclick should calculate and plot the directions between the two points.
I am not overly strong in javascript and this is essentially a mashup of code...can anyone see what I have done wrong and why this wont work?
Javascript is:
<code>
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var arena = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var mapOptions = {
zoom: 12,
center: arena,
panControl: false,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
directionsDisplay.setMap(map);
var marker1 = new MarkerWithLabel({
position: arena,
draggable: false,
raiseOnDrag: false,
map: map,
icon: "images/lax-pin1.png",
labelContent: "Ted Reeve Arena",
labelAnchor: new google.maps.Point(25, 0),
labelClass: "pin", // the CSS class for the label
labelStyle: {opacity: 0.95}
});
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
}
function calcRoute() {
var request = {
origin: GeoMarker,
destination: marker1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</code>
The html is an onclick div tag for the calcRoute function
Thanks for any help....
There is an error reported:
TypeError: e is undefined
for line
map.setCenter(e.latLng);
Event listener
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
should be changed to
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
//map.setCenter(e.latLng);
//map.fitBounds(e.latLngBounds);
map.setCenter(GeoMarker.getPosition());
map.fitBounds(GeoMarker.getBounds());
});
request should be changed to:
var request = {
origin: GeoMarker.getPosition(),
destination: marker1.getPosition(),
travelMode: google.maps.TravelMode.DRIVING
};
because origin/destination expects string or valid LatLng
Update: I forgot this change: marker1 has to be changed to global:
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var marker1;
Okay, I got it to work, but not pretty. This is what I did
function calcRoute() {
var arena1 = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var request = {
origin: GeoMarker.getPosition(),
destination: arena1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});

Uncaught TypeError: Cannot read property 'text' of undefined Google Map [duplicate]

I try to make directions for my current position and marker coordinate. so i get latitude and longitude using getcurrentposition. then, i mark it.
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var node = new google.maps.LatLng(-7.276442,112.791174);
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
directionsDisplay.setMap(map);
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position : pos,
map: map,
title:'Lokasi Anda'
});
var marker1 = new google.maps.Marker({
position : node,
map: map,
title:'Lokasi Anda'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
then, I calculate it using this function.
function calcRoute() {
var request = {
origin:pos,
destination:node,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
but why i can't see direction from pos to node. any suggestion ?
If I call the calcRoute function (and pass in the "pos" and "node" locations, it can't find directions between where I am (in the US) and where the point is located (Raya Its, Sukolilo, Surabaya City, East Java 60117, Republic of Indonesia). The DirectionsService returns a status of "ZERO_RESULTS".
ZERO_RESULTS No route could be found between the origin and destination.
working example
function calcRoute(pos,node) {
var directionsService = new google.maps.DirectionsService();
var request = {
origin:pos,
destination:node,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else { alert("Directions failed: "+status); }
});
}

Marker not showing up in Google Maps api

I have a map that gives directions based on geolocation, however I want a marker to be on the map even before the user gets directions. I can't seem to get the marker to show up when the webpage loads. The code I am using is as follows:
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var directionDisplay, map;
function calculateRoute(from, to) {
// Center initialized to Lafayette IN
var travelMode = $('input[name="travelMode"]:checked').val();
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(40.40541,-86.89048),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var panel = document.getElementById("directionsPanel");
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.40541,-86.89048),
map: map,
title: "Beyond the Box"
});
marker.setMap(map);
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode[travelMode],
unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response,
});
}
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay = new google.maps.DirectionsRenderer({
map: mapObject,
directions: response,
});
directionsDisplay.setPanel(panel);
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
$("#from-link, #to-link").click(function(event) {
event.preventDefault();
var addressId = this.id.substring(0, this.id.indexOf("-"));
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
$("#" + addressId).val(results[0].formatted_address);
else
$("#error").append("Unable to retrieve your address<br />");
});
},
function(positionError){
$("#error").append("Error: " + positionError.message + "<br />");
},
{
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
});
});
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), $("#to").val());
});
});
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<body onLoad="calculateRoute()">
<!-- Start Header -->
<?php include("header.php"); ?>
<!-- End Header -->
You didn't initialize "map" variable.
Try this.
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
marker.setMap(mapObject);

Categories

Resources