Custom Google Map markers on Directions API - google-maps

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();

Related

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>

DirectionsService not working as required by the code

I am trying to make routes between any 2 locations I pass using DirectionsService of google maps. The locations are coming to me dynamically. But the problem I am facing is when the next 2 coordinates come it removes the previous route and displays the new route with the new coordinaates. I also can't use the waypoints because max. 8 waypoints are allowed and I need more than that.
here is my code:
var marker;
var map;
var mapOptions;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function initialize() {
var rendererOptions = {
map : map,
suppressMarkers : true
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
mapOptions = {
zoom: 12,
center: new google.maps.LatLng(23.53265,77.754812)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
}
//var image = 'C:\Users\Samir\Desktop\download.jpg';
var start = new google.maps.LatLng(23.32654,77.32685);
function Plot_Data(latlng){
//end = new google.maps.LatLng(lat,lng);
marker = new google.maps.Marker({
position: latlng ,
map: map
});
var request = {
origin:start,
destination:latlng,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
start = latlng;
}
A directionsRenderer will display only one route at a time. This will add a new one for each time you call the Plot_Data function, but will still be subject to the API rate and query limits:
var marker;
var map;
var mapOptions;
var directionsDisplay = [];
var directionsService = new google.maps.DirectionsService();
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function initialize() {
var rendererOptions = {
map : map,
suppressMarkers : true
}
directionsDisplay.push(new google.maps.DirectionsRenderer(rendererOptions));
mapOptions = {
zoom: 12,
center: new google.maps.LatLng(23.53265,77.754812)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
}
//var image = 'C:\Users\Samir\Desktop\download.jpg';
var start = new google.maps.LatLng(23.32654,77.32685);
function Plot_Data(latlng){
//end = new google.maps.LatLng(lat,lng);
marker = new google.maps.Marker({
position: latlng ,
map: map
});
var request = {
origin:start,
destination:latlng,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[directionsDisplay.length-1].setDirections(response);
directionsDisplay[directionsDisplay.length-1].setMap(map);
directionsDisplay.push(new google.maps.DirectionsRenderer(rendererOptions));
} else alert("directions request failed: " +status);
});
start = latlng;
}

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.

Why won't google map navigate on my web page?

I want to locate a user's location using Geolocation and then navigate between user;s position and a fix point, but Google map just won't navigate and I am using the codes from Google's official documentation!
What's wrong? I am going mad after tried thousands of times,plz help
<script type="text/javascript">
$( "#map-page" ).live( "pageinit", function() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var salon = new google.maps.LatLng(22.981666,120.194301);
var defaultLatLng = new google.maps.LatLng(22.983587,120.22599); // Default to Hollywood, CA when no geolocation support
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
calcRoute(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
console.log(error);
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
var marker = new google.maps.Marker({
position:new google.maps.LatLng(22.981666,120.194301),
map:map,
title:"the salon"
});
}
function calcRoute(latlng) {
var start = latlng;
var end = new google.maps.LatLng(22.981666,120.194301);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
</script>
You forgot to setup directionsDisplay.

Single waypoint working, Multiple waypoints not, any ideas?

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.