Single waypoint working, Multiple waypoints not, any ideas? - google-maps

This code was written for me and used to work, but now the multiple waypoints are not working.
The waypoints are stored as |51.105166,-1.695971|51.105166,-1.695971| in the database.
With only 1 waypoint the maps work, but with more than one they do not show up at all.
Does anybody have any suggestions?
It can be viewed at the link here.
http://www.ridersguide.co.uk/2012/Ride_234
var directionDisplay;
var geocoder;
var directionsService = new google.maps.DirectionsService();
var latlng = new google.maps.LatLng(54.559322587438636, -4.1748046875);
function load() {
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_LEFT}
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var directionRendererOptions ={
suppressMarkers: true,
polylineOptions:{
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 3
}
};
directionsDisplay.setOptions(directionRendererOptions);
var start = '<?php echo $start; ?>';
var end = '<?php echo $end; ?>';
<?php
if($via != null){
echo "var points = [";
foreach($via as $point){
if($point != ""){
echo "{location:";
echo " '".$point."'";
echo "}";
}
}
echo "];\n";
}
?>
var request = {
origin:start,
waypoints: points,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
geocoder.geocode( { 'address': start}, function(results, status) {
var routeStart = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: './images/motorcycling.png',
shadow: './images/motorcycling.shadow.png'
});
});
geocoder.geocode( { 'address': end}, function(results, status) {
var routeEnd = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: './images/motorcyclingend.png',
shadow: './images/motorcycling.shadow.png'
});
});
<?php`

It appears there's a comma missing in your array.
var points = [{location: '51.105166,-1.695971'}{location: '51.105166,-1.695971'}];
should be
var points = [{location: '51.105166,-1.695971'},{location: '51.105166,-1.695971'}];
One way of doing that is to construct that string entirely in php rather than output it piecemeal, and then remove the initial comma you don't need. I've edited this code following the comments received, so just the locations between the [ ] are constructed and the comma removed:
<?php
if($via != null){
$pointstring='';
foreach($via as $point){
if($point != ""){
$pointstring.= ",{location:";
$pointstring.= " '".$point."'";
$pointstring.= "}";
}
}
echo "var points = [".substr($pointstring,1)."];\n";
}
?>
(Code not tested)
There are other ways of outputting the locations piecemeal as you had, but the requirement to have commas between them and not at the end makes it more complex than simply removing one you don't need.

Related

How to draw line between two points in JavaScript - Google Maps Api Route

I have two points on the map, I was able to take the distance using the API, now I need to draw a line between the points so that the user sees all the way. I read that you need to use the polyline, but I unfortunately can not. I take the user's GPS coordinates as point A - and on the map, in the drag event I take the coordinates of point B. You can see an example on the following page: https://tojweb.tj/abb.php
Can you help?
I read that you need to use the polyline, but I unfortunately can not.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
function showPosition(position) {
document.getElementById('mypos_lat').value=position.coords.latitude;
document.getElementById('mypos_lon').value=position.coords.longitude;
//alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude);
}
var darection = new google.maps.DirectionsRenderer;
function initialize() {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(38.583958, 68.780528),
mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: "greedy",
fullscreenControl: false,
disableDefaultUI: true,
zoomControl: true,
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
darection.setMap(map);
google.maps.event.addListener(map, 'dragend', function() {
var centeral = map.getCenter();
//alert(centeral);
var names = centeral.toString();
var names =names.substr(1);
names = names.substring(0, names.length - 1);
console.log(names);
var re = /\s*,\s*/;
var nameList = names.split(re);
document.getElementById('bpos_lat').value=nameList[0];
document.getElementById('bpos_lon').value=nameList[1];
source_a = document.getElementById("mypos_lat").value;
source_b = document.getElementById("mypos_lon").value;
source_d = document.getElementById("bpos_lat").value;
source_e = document.getElementById("bpos_lon").value;
var darection = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//darection.setPanel(document.getElementById('panallocation'));
source = source_a + "," + source_b;
destination = source_d + "," + source_e;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
//Показ алтернативных дорог
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
darection.setDirections(response);
}
});
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 duration = response.rows[0].elements[0].duration.text;
distancefinel = distance.split(" ");
//start_addressfinel = start_address.split(" ");
// $('#distance').val(distancefinel[0]);
console.log(distancefinel[0]);
document.getElementById("distancesa").value = distancefinel[0];
////////// IN THIS STATE I WANT DRAW LINE ///////////////////
} else {
alert("Unable to find the distance between selected locations");
}
});
}
);
$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function(){
var that=$(this);
if(!that.data('win')){
that.data('win',new google.maps.InfoWindow({content:'this is the center'}));
that.data('win').bindTo('position',map,'center');
}
that.data('win').open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You can use the Directions Service of Google Maps JavaScript API to get the directions between 2 points and pass the DirectionsResult to the DirectionsRenderer, which can automatically handle the display in the map.
Here is the code I made which handles the use-case (Geolocating Point A, Draggable Marker B, then having a route between 2 points) from your description. You can also check it here.
Hope this helps!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map, infoWindow, markerA, markerB, drag_pos;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
markerA = new google.maps.Marker({
map: map
});
markerB = new google.maps.Marker({
map: map
});
infoWindow = new google.maps.InfoWindow;
var directionsService = new google.maps.DirectionsService();
var directionsRenderer1 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true
});
var directionsRenderer2 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
polylineOptions: {
strokeColor: "gray"
}
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
map.setZoom(15);
//Put markers on the place
infoWindow.setContent('Your Location');
markerA.setPosition(pos);
markerA.setVisible(true);
markerA.setLabel('A');
markerA.addListener('click', function() {
infoWindow.open(map, markerA);
});
//Get new lat long to put marker B 500m above Marker A
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
var new_latitude = pos.lat + (500 * m);
var new_pos = {
lat: new_latitude,
lng: position.coords.longitude
};
markerB.setPosition(new_pos, );
markerB.setVisible(true);
markerB.setLabel('B');
markerB.setDraggable(true);
//Everytime MarkerB is drag Directions Service is use to get all the route
google.maps.event.addListener(markerB, 'dragend', function(evt) {
var drag_pos1 = {
lat: evt.latLng.lat(),
lng: evt.latLng.lng()
};
directionsService.route({
origin: pos,
destination: drag_pos1,
travelMode: 'DRIVING',
provideRouteAlternatives: true
},
function(response, status) {
if (status === 'OK') {
for (var i = 0, len = response.routes.length; i < len; i++) {
if (i === 0) {
directionsRenderer1.setDirections(response);
directionsRenderer1.setRouteIndex(i);
} else {
directionsRenderer2.setDirections(response);
directionsRenderer2.setRouteIndex(i);
}
}
console.log(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Here is my code. The first commented code does not draw and does not produce any errors. The second code throws an error:
InvalidValueError: at index 0: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value
I know that I am wrong and I am writing my code in the wrong place. I need help to show where the error is and how to fix it so that I understand.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
function showPosition(position) {
document.getElementById('mypos_lat').value=position.coords.latitude;
document.getElementById('mypos_lon').value=position.coords.longitude;
//alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude);
}
var darection = new google.maps.DirectionsRenderer;
function initialize() {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(38.583958, 68.780528),
mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: "greedy",
fullscreenControl: false,
disableDefaultUI: true,
zoomControl: true,
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
darection.setMap(map);
google.maps.event.addListener(map, 'dragend', function() {
var centeral = map.getCenter();
//alert(centeral);
var names = centeral.toString();
var names =names.substr(1);
names = names.substring(0, names.length - 1);
console.log(names);
var re = /\s*,\s*/;
var nameList = names.split(re);
document.getElementById('bpos_lat').value=nameList[0];
document.getElementById('bpos_lon').value=nameList[1];
source_a = document.getElementById("mypos_lat").value;
source_b = document.getElementById("mypos_lon").value;
source_d = document.getElementById("bpos_lat").value;
source_e = document.getElementById("bpos_lon").value;
var darection = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//darection.setPanel(document.getElementById('panallocation'));
source = source_a + "," + source_b;
destination = source_d + "," + source_e;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
//Показ алтернативных дорог
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
darection.setDirections(response);
}
});
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 duration = response.rows[0].elements[0].duration.text;
distancefinel = distance.split(" ");
//start_addressfinel = start_address.split(" ");
// $('#distance').val(distancefinel[0]);
console.log(distancefinel[0]);
document.getElementById("distancesa").value = distancefinel[0];
////////// IN THIS STATE I WANT DRAW LINE ///////////////////
/*
function poliLines(map, source_a, source_b, source_d, source_e){
var routes = [
new google.maps.LatLng(source_a, source_b)
,new google.maps.LatLng(source_d, source_e)
];
var polyline = new google.maps.Polyline({
path: routes
, map: map
, strokeColor: '#ff0000'
, strokeWeight: 5
, strokeOpacity: 0.5
, clickable: false
});
*/
console.log(source);
console.log(destination);
var flightPlanCoordinates = [new google.maps.LatLng(source), new google.maps.LatLng(destination) ];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
} else {
alert("Unable to find the distance between selected locations");
}
});
}
);
$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function(){
var that=$(this);
if(!that.data('win')){
that.data('win',new google.maps.InfoWindow({content:'this is the center'}));
that.data('win').bindTo('position',map,'center');
}
that.data('win').open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Update Pickup location in google map

I want to show the current position based on user lat & long:
Drop off location always stay static but pick up location (icon) need to move as per lat long, but i am not find the correct way my code is:
$(document).ready(function() {
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var infowindow = new google.maps.InfoWindow();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute(pickUpLat,pickUplon,droplat,droplon) {
var pickUpLat = "<?= $pickUpLat ?>";
var pickUplon = "<?= $pickUplon ?>";
var droplat = "<?= $model->drop_off_latitude ?>";
var droplon = "<?= $model->drop_off_longitude ?>";
var start = new google.maps.LatLng(pickUpLat,pickUplon);
var end = new google.maps.LatLng(droplat,droplon);
createMarker(start,"<?= $model->item_delivery_title; ?>","<?= Yii::$app->urlManagerFrontEnd->createAbsoluteUrl('/images/track_route.png')?>");
createMarker(end,"<?= $model->drop_off_address; ?>",'');
var request = {
origin: start,
destination: end,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
function createMarker(latlng,title,icon) {
var marker = new google.maps.Marker({
position: latlng,
animation: google.maps.Animation.DROP,
title: title,
icon: icon,
map: map
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(title);
infowindow.open(map, marker);
});
}
initialize();
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/delivery/map-data'; ?>",
type:"POST",
data:{"delivery_id":<?= $model->id ?>}
})
.done(function(result){
var respon=JSON.parse(result);
if(respon.status==200){
// want to cupdate the pickup location here
}
});
}
setInterval(makeRequest, (3000));
});
Make request function always update the pick up lat and long:
But I am not found any way to move the pick up icon (the van) see image :
The red marker is drop off address and the van is pickup address
You should create two variables for pick up and drop off marker. Also your createMarker function should return marker instance. After you receive request from server update pickUpMarker position.
$(document).ready(function() {
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var infowindow = new google.maps.InfoWindow();
var map;
var pickUpMarker, dropToMarker; // add marker variables
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute(pickUpLat,pickUplon,droplat,droplon) {
var pickUpLat = "<?= $pickUpLat ?>";
var pickUplon = "<?= $pickUplon ?>";
var droplat = "<?= $model->drop_off_latitude ?>";
var droplon = "<?= $model->drop_off_longitude ?>";
var start = new google.maps.LatLng(pickUpLat,pickUplon);
var end = new google.maps.LatLng(droplat,droplon);
if(!pickUpMarker) {
pickUpMarker = createMarker(start,"<?= $model->item_delivery_title; ?>","<?= Yii::$app->urlManagerFrontEnd->createAbsoluteUrl('/images/track_route.png')?>");
} else {
pickUpMarker.setPosition(start)
}
if(!dropToMarker) {
dropToMarker = createMarker(end,"<?= $model->drop_off_address; ?>",'');
} else {
dropToMarker.setPosition(start)
}
var request = {
origin: start,
destination: end,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
function createMarker(latlng,title,icon) {
var marker = new google.maps.Marker({
position: latlng,
animation: google.maps.Animation.DROP,
title: title,
icon: icon,
map: map
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(title);
infowindow.open(map, marker);
});
return marker;
}
initialize();
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/delivery/map-data'; ?>",
type:"POST",
data:{"delivery_id":<?= $model->id ?>}
})
.done(function(result){
var respon=JSON.parse(result);
if(respon.status==200){
// want to cupdate the pickup location here
pickUpMarker.setPosition(result.position)
}
});
}
setInterval(makeRequest, (3000));
});

The direction does not show my current location and the destination

See this image.
I try to show my current location to the destination but the direction does not show up in the map, it just show the route at panel only.
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions =
{
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
displayRoute(directionsService, directionsDisplay);
function displayRoute(service, display) {
service.route({
origin: coords,
destination: new google.maps.LatLng(5.409722, 100.313319),
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
});
The map does not show the direction from my current location to destination.
When you create your google.maps.DirectionsRenderer, the map is undefined. Either create the google.maps.DirectionsRenderer after the map, or call .setMap on it once the map is defined.
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions = {
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
displayRoute(directionsService, directionsDisplay);
proof of concept fiddle
code snippet:
var geocoder;
var map;
// [ 0 ]: Tapah, Perak, Malaysia (4.19773, 101.261529)
function initialize() {
var latitude = 4.19773;
var longitude = 101.261529;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions = {
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
displayRoute(directionsService, directionsDisplay);
function displayRoute(service, display) {
service.route({
origin: coords,
destination: new google.maps.LatLng(5.409722, 100.313319),
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<div id="right-panel"></div>

Google Map direction

I have a google map on a website where I show the position of a business with a custom marker, also, I show the routes to get to the place but I can't seem to understand how to use a custom icon for the START position...
Here is the code I use:
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({draggable: true,suppressMarkers: true});
var latlng = new google.maps.LatLng(45.86140239,-74.062538);
var myOptions = {
zoom:13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng,
mapTypeControl: false,
panControl: false,
streetViewControl: false,
zoomControl: false,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Marqueur sur le bureau
var icon = {url: 'marker001c.png'};
var headquartersMarker = new google.maps.Marker({
position: latlng,
map: map,
animation: google.maps.Animation.DROP,
icon: icon,
zIndex:99999
});
directionsDisplay.setMap(map);
}
// Calcule de la route
function calcRoute() {
var start = document.getElementById("start").value;
var end = new google.maps.LatLng(45.86140239,-74.062538);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
directionsDisplay.setPanel(document.getElementById('panel'));
});
var starticon = new google.maps.MarkerImage('test.png');
var marker = new google.maps.Marker({
position:start,
map: map,
icon: starticon,
});
makeMarker({
position: new google.maps.LatLng(60.17295,24.93981),
content: "Some text in the info bubble.",
title: "Tooltip text"
});
}
</script>
By using this code it show me the end icon (my main marker) but I can't change the start icon. Any idea?
start position as string could be used for DirectionsService but for marker you have to change position to LatLng.
See Geocoding Service
For geocoding add new global variable:
...
var map;
var geocoder;
And initialize it:
function initialize() {
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer({draggable: true, suppressMarkers: true});
...
And get the latlng of the start 'address' after directionsService.route():
geocoder.geocode( { 'address': start}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var starticon = new google.maps.MarkerImage('images/start.png');
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: starticon
});
} else {
alert("Geocode failed with status: " + status);
}
});
See example at jsBin. Note: it won't work there because I use my icon images so put in paths to your icon images.

Custom Google Map markers on Directions API

I'm totally new to the Google maps api, and after putting together several examples found around the web, I'm struggling on the last hurdle of adding custom markers to the directions. Here's my code:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng([[showMapLatitude]],[[showMapLongitude]]);
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var stylez = [
{
featureType: "all",
elementType: "all",
stylers: [
{ saturation: -100 }
]
}
];
var image = new google.maps.MarkerImage('/icon.png',
new google.maps.Size(20, 33),
new google.maps.Point(0,0),
new google.maps.Point(10,33)
);
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var mapType = new google.maps.StyledMapType(stylez, { name:"Grayscale" });
map.mapTypes.set('tehgrayz', mapType);
map.setMapTypeId('tehgrayz');
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"[[*pagetitle]]",
icon: image
});
}
function calcRoute() {
$(".storeDetails").hide();
$(".storeAdress").hide();
$(".backtocontact").show();
var start = document.getElementById("routeStart").value;
var end = "[[showMapLatitude]],[[showMapLongitude]]";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
There's an example of how to do it here: Change individual markers in google maps directions api V3
But being a noob, I can't seem to drop that in the right place here, it either errors or does nothing.
Change
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
To
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var leg = response.routes[ 0 ].legs[ 0 ];
makeMarker( leg.start_location, icons.start, "title" );
makeMarker( leg.end_location, icons.end, 'title' );
}
});
And don't forget to add makeMarker() function.
Also you will need both start and end icons
In reply to comment in my other answer
To remove original custom marker and show default marker
Delete
var image = new google.maps.MarkerImage('/icon.png',
new google.maps.Size(20, 33),
new google.maps.Point(0,0),
new google.maps.Point(10,33)
);
and
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"[[*pagetitle]]",
icon: image
});
Also change
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
To
directionsDisplay = new google.maps.DirectionsRenderer();