Responsive friendly square openstreetmap - html

I'm using this code to display an openstreetmap. It works great on a desktop display but it's not very responsive friendly. I like to have a square sized map. I'm having some problems to find the right parameters for a responsive hight and width.
How can I set it to a 1:1 ratio?
My demo of the below source code: https://jsfiddle.net/uyn9posg/
<link id="cf7-map-field-leaflet-css" rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" />
<script id="cf7-map-field-leaflet-js" src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<div style="position:relative">
<div id="CF7MapFieldDiv" style="height:600px;width:100%"></div>
<span style="position:absolute;right:0px;bottom:20px;font: 12px Arial,Helvetica,sans-serif;background-color: rgba(255, 255, 255, 0.698);padding:2px 7px;z-index: 1000;" >
Marker bei: <span id="CF7MapMarkerAt">none</span>
</span>
</div>
<script>
var map;
var marker;
function updateMarkerPosition(e) {
//var markerLatLang = [e.lat.toFixed(6), e.lng.toFixed(6)].join(',');
var markerLong = e.lng.toFixed(6);
var markerLat = e.lat.toFixed(6);
//document.getElementById('CF7MapMarkerAt').innerHTML = markerLatLang;
document.getElementById('CF7MapMarkerAt').innerHTML = "Lat="+markerLat +", Long="+markerLong;
var hidd = document.getElementById('CF7MapLocationHidden');
var hidd2 = document.getElementById('CF7MapLocationHidden_long');
var hidd3 = document.getElementById('CF7MapLocationHidden_lat');
var hidd4 = document.getElementById('CF7MapLocationHidden_zoom');
//var val = [map.getZoom(), markerLatLang].join(';');
var zoomstufe = map.getZoom();
//if (!!hidd) { hidd.value = val; }
if (!!hidd2) { hidd2.value = markerLong; }
if (!!hidd3) { hidd3.value = markerLat; }
if (!!hidd4) { hidd4.value = zoomstufe; }
}
function onMarkerDrag(e) {
updateMarkerPosition(marker.getLatLng());
}
function onMapClick(e) {
map.removeLayer(initMarker);
if (marker === undefined) {
var markerIcon = L.icon({
iconUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-icon.png',
shadowUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-shadow.png',
iconSize: [25, 41],
shadowSize: [41, 41],
shadowAnchor: [15, 41]
});
marker = L.marker(e.latlng, {
icon: markerIcon,
draggable: true
}).addTo(map);
marker.on('drag', onMarkerDrag);
} else {
marker.setLatLng([e.latlng.lat, e.latlng.lng]);
}
updateMarkerPosition(e.latlng);
}
var initMarker = {};
function initmap() {
// set up the map
map = new L.Map('CF7MapFieldDiv');
// create the tile layer with correct attribution
var mapUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var mapAttrib = '© OpenStreetMap contributors';
var mapTile = new L.TileLayer(mapUrl, {
minZoom: 2,
maxZoom: 18,
attribution: mapAttrib
});
map.addLayer(mapTile);
// set default view (London)
//map.setView(new L.LatLng(51.501, -0.105), 8);
map.setView(new L.LatLng(47.77929097015571, 9.609822830498674), 9);
initMarker = L.marker([47.77929097015571, 9.609822830498674], {
iconUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-icon.png',
shadowUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-shadow.png',
iconSize: [25, 41],
shadowSize: [41, 41],
shadowAnchor: [15, 41], draggable: true
}).addTo(this.map);
// add events
map.on('click', onMapClick);
}
initmap();
</script>

Constraining to the Smallest Viewport Dimension
Not sure if this would be an alright way of doing for your use case. But I usually like to take the smaller (minimum) of the viewport height viewport width, min(100vh,100vw) and use that to set the height and width of the element I'm trying to keep a square 1:1 aspect ratio. This will also work for other fractions of viewport height and width. Effectively, this will contain the square to the smallest dimension. Press the blue Run code snippet button below to see the results and test the responsiveness using the full page link:
Minimal Example:
.Rectangle {
--Dimensions: min(80vh, 80vw);
height: var(--Dimensions);
width: var(--Dimensions);
position: absolute;
top: calc(50% - var(--Dimensions)/2);
left: calc(50% - var(--Dimensions)/2);
background-color: cyan;
}
<div class="Rectangle"></div>
Map Implementation:
<link id="cf7-map-field-leaflet-css" rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" />
<script id="cf7-map-field-leaflet-js" src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<div style="position:relative">
<div id="CF7MapFieldDiv" style="height:min(100vh,100vw); width:min(100vh,100vw); left: calc(50% - min(100vh,100vw)/2)"></div>
<span style="position:absolute;right:0px;bottom:20px;font: 12px Arial,Helvetica,sans-serif;background-color: rgba(255, 255, 255, 0.698);padding:2px 7px;z-index: 1000;" >
Marker bei: <span id="CF7MapMarkerAt">none</span>
</span>
</div>
<script>
var map;
var marker;
function updateMarkerPosition(e) {
//var markerLatLang = [e.lat.toFixed(6), e.lng.toFixed(6)].join(',');
var markerLong = e.lng.toFixed(6);
var markerLat = e.lat.toFixed(6);
//document.getElementById('CF7MapMarkerAt').innerHTML = markerLatLang;
document.getElementById('CF7MapMarkerAt').innerHTML = "Lat="+markerLat +", Long="+markerLong;
var hidd = document.getElementById('CF7MapLocationHidden');
var hidd2 = document.getElementById('CF7MapLocationHidden_long');
var hidd3 = document.getElementById('CF7MapLocationHidden_lat');
var hidd4 = document.getElementById('CF7MapLocationHidden_zoom');
//var val = [map.getZoom(), markerLatLang].join(';');
var zoomstufe = map.getZoom();
//if (!!hidd) { hidd.value = val; }
if (!!hidd2) { hidd2.value = markerLong; }
if (!!hidd3) { hidd3.value = markerLat; }
if (!!hidd4) { hidd4.value = zoomstufe; }
}
function onMarkerDrag(e) {
updateMarkerPosition(marker.getLatLng());
}
function onMapClick(e) {
map.removeLayer(initMarker);
if (marker === undefined) {
var markerIcon = L.icon({
iconUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-icon.png',
shadowUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-shadow.png',
iconSize: [25, 41],
shadowSize: [41, 41],
shadowAnchor: [15, 41]
});
marker = L.marker(e.latlng, {
icon: markerIcon,
draggable: true
}).addTo(map);
marker.on('drag', onMarkerDrag);
} else {
marker.setLatLng([e.latlng.lat, e.latlng.lng]);
}
updateMarkerPosition(e.latlng);
}
var initMarker = {};
function initmap() {
// set up the map
map = new L.Map('CF7MapFieldDiv');
// create the tile layer with correct attribution
var mapUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var mapAttrib = '© OpenStreetMap contributors';
var mapTile = new L.TileLayer(mapUrl, {
minZoom: 2,
maxZoom: 18,
attribution: mapAttrib
});
map.addLayer(mapTile);
// set default view (London)
//map.setView(new L.LatLng(51.501, -0.105), 8);
map.setView(new L.LatLng(47.77929097015571, 9.609822830498674), 9);
initMarker = L.marker([47.77929097015571, 9.609822830498674], {
iconUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-icon.png',
shadowUrl: 'http://cdn.leafletjs.com/leaflet-0.4.4/images/marker-shadow.png',
iconSize: [25, 41],
shadowSize: [41, 41],
shadowAnchor: [15, 41], draggable: true
}).addTo(this.map);
// add events
map.on('click', onMapClick);
}
initmap();
</script>

Related

Integrating maps in Cytoscape

I am currently using Cytoscape JS to visualize a network but I would like to overlay the graph on a world map and plot the nodes to specific locations. The Tokyo Railways Demo is similar to what I have imagined but the background is black. I want my map to look like the google maps and have similar zoom in and out capabilities. It would be great if there is a way to integrate the google maps in the Cytoscape graph.
Cytoscape.js on Google Maps, a demo code based on a sample overlay-simple. The current state is rough, but it works.
Try running the code below in full screen. To zoom IN/OUT, use press_Ctrl + scroll_wheel.
The best platform to test this code is jsfiddle.net, by forking the original code and replacing parts with the code presented here.
/*
Status: google_APIkey is good for development only
*/
// This example creates a custom overlay called CyOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.
// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class therefore
// it's simpler to load the API synchronously, using
// google.maps.event.addDomListener().
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.
// some data here
var cyto_divid = 'cy'; //outside, below gmaps
var goverlay_id = 'cy4'; //overlay on gmaps
var timeoutsec = 500; //millisec
var cy;
var base_dc = 0.03; //TODO: derive a formula
var lon_ext = 25; //extent in lng
var lonmin = 90.0; //90
var latmin = 0; //0
var lon_cor = lon_ext*base_dc;
var lat_ext = lon_ext; //extent in lat
var lonmax = lonmin + lon_ext;
var lonmid = (lonmin+lonmax)/2;
var lonmax2 = lonmax + lon_cor;
var latmax = latmin + lat_ext;
var latmid = (latmin+latmax)/2;
var latlng = { lat: latmin, lng: lonmin};
var latlng2 = { lat: latmax, lng: lonmax2};
var clatlng = { lat: latmid, lng: lonmid};
var cbottom = { lat: latmin, lng: lonmid};
function lnglat2xy(lon, lat) {
let w = 500;
let h = 500;
let L = lonmax2-lonmin;
let B = latmax-latmin;
let y = (B-(lat-latmin))*h/B;
let x = (lon-lonmin)*w/L;
return {x: x, y: y};
}
var bkk = lnglat2xy(100.494, 13.75);
var bda = lnglat2xy(95.502586, 5.412598);
var hoc = lnglat2xy(106.729, 10.747);
var han = lnglat2xy(105.90673, 21.03176);
var chi = lnglat2xy(99.837, 19.899);
var nay = lnglat2xy(96.116, 19.748);
var overlay;
CyOverlay.prototype = new google.maps.OverlayView();
// Initialize the map and the custom overlay.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5, //11,
center: {
lat: (latmax+latmin)/2, //62.323907,
lng: (lonmax2+lonmin)/2 //-150.109291
},
mapTypeId: 'roadmap' //
});
map.addListener('zoom_changed', function() {
setTimeout(function delay() {
cy.fit(cy.$('#LL, #UR'));
}, timeoutsec)
});
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(latmin, lonmin), //62.281819, -150.287132)
new google.maps.LatLng(latmax, lonmax2)); //62.400471, -150.005608))
// The photograph is courtesy of the U.S. Geological Survey.
var srcImage;
/*srcImage = 'https://developers.google.com/maps/documentation/' +
'javascript/examples/full/images/talkeetna.png';*/
// The custom CyOverlay object contains the USGS image,
// the bounds of the image, and a reference to the map.
overlay = new CyOverlay(bounds, srcImage, map);
// init cytoscape
setTimeout(function delay() {
cyto_run();
}, timeoutsec)
}
/** #constructor */
function CyOverlay(bounds, image, map) {
// Initialize all properties.
this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;
// Define a property to hold the image's div. We'll
// actually create this div upon receipt of the onAdd()
// method so we'll leave it null for now.
this.div_ = null;
// Explicitly call setMap on this overlay.
this.setMap(map);
}
/**
* onAdd is called when the map's panes are ready and the overlay has been
* added to the map.
*/
CyOverlay.prototype.onAdd = function() {
var div = document.createElement('div');
div.id = goverlay_id;
div.style.borderStyle = 'dashed';
//div.style.backgroundColor = rgba(76,76,76,0.25);
div.style.opacity = 0.8;
div.style.borderWidth = '1px';
div.style.borderColor = 'gray';
div.style.position = 'absolute';
// Create the img element and attach it to the div.
var img = document.createElement('img');
img.src = this.image_;
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'absolute';
//div.appendChild(img); //ignore overlay img
this.div_ = div;
// Add the element to the "overlayLayer" pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
CyOverlay.prototype.draw = function() {
// We use the south-west and north-east
// coordinates of the overlay to peg it to the correct position and size.
// To do this, we need to retrieve the projection from the overlay.
var overlayProjection = this.getProjection();
// Retrieve the south-west and north-east coordinates of this overlay
// in LatLngs and convert them to pixel coordinates.
// We'll use these coordinates to resize the div.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's div to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
/*
cytoscape needs regen here
*/
setTimeout(function delay() {
cy.fit(cy.$('#LL, #UR'));
}, timeoutsec)
};
// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
CyOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
google.maps.event.addDomListener(window, 'load', initMap);
/* ___________cytoscape.js code____________ */
function cyto_run() {
cy = cytoscape({
container: document.getElementById(goverlay_id),
elements: {
nodes: [
{data: {id: "LL", nname: "LowerLeft"},
classes: "controlpoint",
position: {x: 0, y: 500}},
{data: {id: "UL", nname: "UpperLeft"},
classes: "controlpoint",
position: {x: 0, y: 0}},
{data: {id: "UR", nname: "UpperRight"},
classes: "controlpoint",
position: {x: 500, y: 0}},
{data: {id: "LR", nname: "LowerRight"},
classes: "controlpoint",
position: {x: 500, y: 500}},
{data: {id: "bkk", name: "Bangkok"}, classes: "datapoint", position: {x: bkk.x, y: bkk.y}},
{data: {id: "bda", name: "Banda"}, classes: "datapoint", position: {x: bda.x, y: bda.y}},
{data: {id: "hoc", name: "Hochi"}, classes: "datapoint", position: {x: hoc.x, y: hoc.y}},
{data: {id: "han", name: "Hanoi"}, classes: "datapoint", position: {x: han.x, y: han.y}},
{data: {id: "nay", name: "Nay"}, classes: "datapoint", position: {x: nay.x, y: nay.y}},
],
edges: [
{data: {source: "nay", target: "bda", label: "NAB"},
classes: 'autorotate'},
{data: {source: "nay", target: "han", label: "NAH"},
classes: 'autorotate'},
{data: {source: "bda", target: "bkk", label: "dgfh"}},
{data: {source: "hoc", target: "bkk", label: "tert"}},
{data: {source: "hoc", target: "bda", label: "HOB"},
classes: 'autorotate'},
{data: {source: "hoc", target: "han", label: "HOH"},
classes: 'autorotate'},
{data: {source: "han", target: "bkk", label: "terf"}},
{data: {id: "LLUR" , source: "LL", target: "UR"},
classes: "controlline"},
{data: {id: "ULLR" , source: "UL", target: "LR"},
classes: "controlline"},
]
},
style: [
{
selector: "node.datapoint",
style: {
shape: "ellipse",
width: '12px',
height: '12px',
"background-color": "blue",
label: "data(name)",
opacity: 0.85,
"text-background-color": "yellow"
}
},
{
selector: "node.controlpoint",
style: {
shape: "triangle",
width: '4px',
height: '4px',
"background-color": "blue",
label: "data(id)",
opacity: 0.85,
}
},
{
selector: "edge[label]",
style: {
label: "data(label)",
width: 2,
"line-color": "#909",
"target-arrow-color": "#f00",
"curve-style": "bezier",
"target-arrow-shape": "vee",
//"target-arrow-fill": "red",
"arrow-scale": 1.0,
}
},
{
"selector": ".autorotate",
"style": {
"edge-text-rotation": "autorotate"
}
},
{
"selector": ".controlline",
"style": {
width: "2px",
"line-color": "green",
opacity: 0.35
}
},
{
selector: ".highlight",
css: {
"background-color": "yellow"
}
}
],
layout: {
name: "preset"
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#cy {
width: 600px;
height: 600px;
position: absolute;
}
#cy4 {
width: 600px;
height: 600px;
position: absolute;
}
<b>Cytoscape on Google Maps</b>
<div id="map"></div>
<div id="cy"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.9.2/cytoscape.min.js"></script>
There is a plugin cytoscape-mapbox-gl, which intergrates Cytoscape.js and Mapbox GL JS. It can be used with any raster or vector basemap layer.
I'm the author.

How to hide the numbers on a cluster marker in Google Maps?

So I have this:
But what I want is this:
I'm pretty sure there should be an option I can specify here:
var options = {
gridSize: 80,
imagePath: imagePath ,
someOption : iAmMissing ??
}
var mc = new MarkerClusterer(map, mapmarkers, options);
google.maps.event.addListener(mc, 'clusteringend', function(){
setTimeout(fixMyPageOnce, 1);
});
But I can't seem to find an option. Is this the right place or is there another way I can get rid of the numbers in the circles?
You can just use the "styles" options and set the "textSize" option slightly above 0:
var options = {
gridSize: 80,
styles: [{
url: imagePath,
height: 29,
width: 29,
anchor: [0, 0],
textSize: 0.001
}, {
url: imagePath,
height: 49,
width: 49,
anchor: [0, 0],
textSize: 0.001
}, {
url: imagePath,
width: 65,
height: 65,
anchor: [0, 0],
textSize: 0.001
}]
}
It is working for me.
Just set textColor to transparent
var options = {
textColor: 'transparent',
gridSize: 80,
imagePath: imagePath ,
someOption : iAmMissing ??
}
Create a custom "calculator" function that sets the "text" property of the return value to "".
calculator: function(markers, numStyles) {
var index = 0;
var count = markers.length.toString();
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: "",
index: index,
title: count
};
}
proof of concept fiddle
code snippet:
function initialize() {
var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
var mapOptions = {
zoom: 12,
center: center,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers.length; i++) {
addMarker(markers[i]);
}
markerCluster = new MarkerClusterer(map, gmarkers, {
imagePath: 'https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m',
calculator: function(markers, numStyles) {
var index = 0;
var title = "";
var count = markers.length.toString();
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: "",
index: index,
title: count
};
}
});
}
var gmarkers = [];
var markers = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
var markerCluster;
// Our markers
markers = [
['0', 'Title 1', 52.4357808, 4.991315699999973, 'car'],
['1', 'Title 2', 52.4357808, 4.981315699999973, 'third'],
['2', 'Title 3', 52.4555687, 5.039231599999994, 'car'],
['3', 'Title 4', 52.4555687, 5.029231599999994, 'second']
];
function addMarker(marker) {
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
var marker = new google.maps.Marker({
title: title,
position: pos,
map: map
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker1, content) {
return function() {
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, content));
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map-canvas {
width: 100%;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://unpkg.com/#googlemaps/markerclustererplus/dist/index.min.js"></script>
<div id="map-canvas"></div>

Exporting kineticJS to image (datatoURL)

I ran into an issue while using kineticJS to create multiple stages.
I am trying to export multiple "stages" to images but I cant get past exporting the first stage, the datatoURL function doesnt seem to be working, and it breaks my script, or perhaps I'm calling it at the wrong location...
When the user clicks the save button, each stage should be converted to an image and displayed on the same page.
Can anyone tell me why the first stage is not being displayed as an image on the page?
Thanks in advance
Here is the code that puts the stage data into the image placeholder on the page.
document.getElementById('save').addEventListener('click', function() {
stage.toDataURL({
callback: function(dataUrl) {
document.getElementById("canvasimg").src = dataUrl;
document.getElementById("canvasimg").style.display = "inline";
}
});
}, false);
below is the full code:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Canvas</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript' src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.1.min.js"></script>
<script type='text/javascript'>
$(window).load(function(){
var highlightWidth = 8;
var stage = new Kinetic.Stage({
container: 'container1',
width: 300,
height: 100
});
var layer = new Kinetic.Layer();
stage.add(layer);
document.getElementById('save').addEventListener('click', function() {
stage.toDataURL({
callback: function(dataUrl) {
document.getElementById("canvasimg").src = dataUrl;
document.getElementById("canvasimg").style.display = "inline";
}
});
}, false);
var dropzone = new Kinetic.Stage({
container: 'container2',
width: 300,
height: 100
});
var dropLayer = new Kinetic.Layer();
dropzone.add(dropLayer);
addBackground(stage, layer, dropLayer);
layer.draw();
addBackground(dropzone, dropLayer, layer);
dropLayer.draw();
var stage2 = new Kinetic.Stage({
container: 'container3',
width: 300,
height: 100
});
var layer2 = new Kinetic.Layer();
stage2.add(layer2);
var dropzone2 = new Kinetic.Stage({
container: 'container4',
width: 300,
height: 100
});
var dropLayer2 = new Kinetic.Layer();
dropzone2.add(dropLayer2);
addBackground(stage2, layer2, dropLayer2);
layer2.draw();
addBackground(dropzone2, dropLayer2, layer2);
dropLayer2.draw();
var images = {};
var URLs = {
house1: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg',
house2: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg',
house3: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg'
};
loadImages(URLs, start);
function start() {
var house1 = kImage(images.house1, 10, 10, 50, 50, layer);
var house2 = kImage(images.house2, 75, 10, 50, 50, layer);
var house3 = kImage(images.house3, 140, 10, 50, 50, layer);
layer.draw();
var house1 = kImage(images.house1, 10, 10, 50, 50, dropLayer);
var house2 = kImage(images.house2, 75, 10, 50, 50, dropLayer);
var house3 = kImage(images.house3, 140, 10, 50, 50, dropLayer);
dropLayer.draw();
var house1 = kImage(images.house1, 10, 10, 50, 50, layer2);
var house2 = kImage(images.house2, 75, 10, 50, 50, layer2);
var house3 = kImage(images.house3, 140, 10, 50, 50, layer2);
layer.draw();
var house1 = kImage(images.house1, 10, 10, 50, 50, dropLayer2);
var house2 = kImage(images.house2, 75, 10, 50, 50, dropLayer2);
var house3 = kImage(images.house3, 140, 10, 50, 50, dropLayer2);
dropLayer.draw();
}
function swapStagesIfSelected(sourceLayer, destinationLayer, startX, startY) {
var elements = sourceLayer.get("Image");
var totalWidth = 0;
var maxHeight = -999;
var layerWidth = destinationLayer.getStage().getWidth();
var layerHeight = destinationLayer.getStage().getHeight();
for (var i = 0; i < elements.length; i++) {
if (elements[i].isSelected) {
totalWidth += elements[i].getWidth();
maxHeight = Math.max(elements[i].getHeight(), maxHeight);
}
}
if (startX + totalWidth > layerWidth) {
startX = layerWidth - totalWidth - 15;
}
if (startY + maxHeight > layerHeight) {
startY = layerHeight - maxHeight - 15;
}
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.isSelected) {
var img = element.getImage();
kImage(img, startX, startY, element.getWidth(), element.getHeight(), destinationLayer);
startX += element.getWidth() + 10;
element.remove();
}
}
sourceLayer.draw();
destinationLayer.draw();
}
function kImage(image, x, y, width, height, theLayer) {
var image = new Kinetic.Image({
image: image,
x: x,
y: y,
width: width,
height: height,
strokeWidth: 0,
stroke: "white",
draggable: true
});
image.myLayer = theLayer;
image.isSelected = false;
image.on("click", function () {
this.myLayer.draw();
});
image.myLayer.add(image);
return (image);
}
function addBackground(theStage, theLayer, otherLayer) {
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: theStage.getWidth(),
height: theStage.getHeight(),
fill: "white",
stroke: "blue",
strokeWidth: 1
});
background.on("click", function () {
var pos = theStage.getMousePosition();
var mouseX = parseInt(pos.x);
var mouseY = parseInt(pos.y);
swapStagesIfSelected(otherLayer, theLayer, mouseX, mouseY);
});
theLayer.add(background);
}
function loadImages(URLs, callback) {
var loaded = 0;
var needed = 0;
for (var url in URLs) {
needed++;
console.log(url);
}
for (var url in URLs) {
images[url] = new Image();
images[url].onload = function () {
if (++loaded >= needed) {
callback(images);
}
};
images[url].src = URLs[url];
}
}
});
</script>
</head>
<body>
<div id="container1"></div>
<div id="container2"></div>
<div id="container3"></div>
<div id="container4"></div>
<img style="background:url(test1.png);" id="canvasimg" style="display:none;">
<button id="save">Save as image</button>
</body>
</html>

Unable to change the title style of the marker

I am trying to change the title of the marker style
This is the HTML i am constructing and passing
But its not applying style
Could you please let em know how to resolve this
function createMarker(latlng, html) {
var tooltiponclcik = 'Company Name : 1 , <br> ' + 'Sales Off Name : 2 , <br>' + 'Warehouse Name : 3 ';
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5,
title:tooltiponclcik
});
markerArray.push(marker); //push local var marker into global array
}
This is my fiddle
http://jsfiddle.net/6wp7enot/16/
The title property of the Marker is used to create rollover text. That text cannot be styled with HTML formatting tags (it can only be straight text).
If you want to create formatted text the appears on mouseover you can, but you need to code that yourself.
proof of concept fiddle, using the code from my answer to: title of a marker of google map marker API
code snippet:
function createMarker(latlng, html) {
var tooltiponclcik = 'Company Name : 1 , <br> ' + 'Sales Off Name : 2 , <br>' + 'Warehouse Name : 3 ';
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5,
tooltip: tooltiponclcik
});
var tooltip = new Tooltip({
map: map
}, marker);
tooltip.bindTo("text", marker, "tooltip");
google.maps.event.addListener(marker, 'mouseover', function() {
tooltip.addTip();
tooltip.getPos2(marker.getPosition());
});
google.maps.event.addListener(marker, 'mouseout', function() {
tooltip.removeTip();
});
markerArray.push(marker); //push local var marker into global array
}
var geocoder;
var map;
var markerArray = [];
function initialize() {
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 normalMarker = new google.maps.Marker({
position: {
lat: 37.43,
lng: -122.14
},
title: "normal tooltip",
map: map
});
// from https://stackoverflow.com/questions/19279199/title-of-a-marker-of-google-map-marker-api/
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37.442, -122.142),
map: map,
tooltip: '<B>This is a customized tooltip</B>'
});
var tooltip = new Tooltip({
map: map
}, marker);
tooltip.bindTo("text", marker, "tooltip");
google.maps.event.addListener(marker, 'mouseover', function() {
tooltip.addTip();
tooltip.getPos2(marker.getPosition());
});
google.maps.event.addListener(marker, 'mouseout', function() {
tooltip.removeTip();
});
//your code
createMarker(new google.maps.LatLng(37.45, -122.162), "stuff for infowindow");
}
google.maps.event.addDomListener(window, "load", initialize);
// The custom tooltip class
// Constructor function
function Tooltip(opts, marker) {
// Initialization
this.setValues(opts);
this.map_ = opts.map;
this.marker_ = marker;
var div = this.div_ = document.createElement("div");
// Class name of div element to style it via CSS
div.className = "tooltip";
this.markerDragging = false;
}
Tooltip.prototype = {
// Define draw method to keep OverlayView happy
draw: function() {},
visible_changed: function() {
var vis = this.get("visible");
this.div_.style.visibility = vis ? "visible" : "hidden";
},
getPos: function(e) {
var projection = this.getProjection();
// Position of mouse cursor
var pixel = projection.fromLatLngToDivPixel(e.latLng);
var div = this.div_;
// Adjust the tooltip's position
var gap = 15;
var posX = pixel.x + gap;
var posY = pixel.y + gap;
var menuwidth = div.offsetWidth;
// Right boundary of the map
var boundsNE = this.map_.getBounds().getNorthEast();
boundsNE.pixel = projection.fromLatLngToDivPixel(boundsNE);
if (menuwidth + posX > boundsNE.pixel.x) {
posX -= menuwidth + gap;
}
div.style.left = posX + "px";
div.style.top = posY + "px";
if (!this.markerDragging) {
this.set("visible", true);
}
},
getPos2: function(latLng) { // This is added to avoid using listener (Listener is not working when Map is quickly loaded with icons)
var projection = this.getProjection();
// Position of mouse cursor
var pixel = projection.fromLatLngToDivPixel(latLng);
var div = this.div_;
// Adjust the tooltip's position
var gap = 5;
var posX = pixel.x + gap;
var posY = pixel.y + gap;
var menuwidth = div.offsetWidth;
// Right boundary of the map
var boundsNE = this.map_.getBounds().getNorthEast();
boundsNE.pixel = projection.fromLatLngToDivPixel(boundsNE);
if (menuwidth + posX > boundsNE.pixel.x) {
posX -= menuwidth + gap;
}
div.style.left = posX + "px";
div.style.top = posY + "px";
if (!this.markerDragging) {
this.set("visible", true);
}
},
addTip: function() {
var me = this;
var g = google.maps.event;
var div = me.div_;
div.innerHTML = me.get("text").toString();
// Tooltip is initially hidden
me.set("visible", false);
// Append the tooltip's div to the floatPane
me.getPanes().floatPane.appendChild(this.div_);
// In IE this listener gets randomly lost after it's been cleared once.
// So keep it out of the listeners array.
g.addListener(me.marker_, "dragend", function() {
me.markerDragging = false;
});
// Register listeners
me.listeners = [
// g.addListener(me.marker_, "dragend", function() {
// me.markerDragging = false; }),
g.addListener(me.marker_, "position_changed", function() {
me.markerDragging = true;
me.set("visible", false);
}),
g.addListener(me.map_, "mousemove", function(e) {
me.getPos(e);
})
];
},
removeTip: function() {
// Clear the listeners to stop events when not needed.
if (this.listeners) {
for (var i = 0, listener; listener = this.listeners[i]; i++) {
google.maps.event.removeListener(listener);
}
delete this.listeners;
}
// Remove the tooltip from the map pane.
var parent = this.div_.parentNode;
if (parent) parent.removeChild(this.div_);
}
};
function inherit(addTo, getFrom) {
var from = getFrom.prototype; // prototype object to get methods from
var to = addTo.prototype; // prototype object to add methods to
for (var prop in from) {
if (typeof to[prop] == "undefined") to[prop] = from[prop];
}
}
// Inherits from OverlayView from the Google Maps API
inherit(Tooltip, google.maps.OverlayView);
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
.tooltip {
position: absolute;
width: 145px;
padding: 5px;
border: 1px solid gray;
font-size: 9pt;
font-family: Verdana;
background-color: #fff;
color: #000;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
$(document).ready(function () {
var a = 10.109240;
var b = 76.354261;
var c = '<div style="font-weight: 500;"><dd style="color: #2196F3;">change text color <i class="fa fa-map-marker"></i></dd><dd style="color: red;">change text color <i class="fa fa-check"></i></dd></div>';
var map;
var host = window.location.origin;
var host0 = window.location.hostname;
var host1 = window.location.pathname;
var icon = "/images/map-icon.png";
map = new google.maps.Map(document.getElementById('map_canvas'),{
center: { lat: a, lng: b },
zoom: 8,
icon : icon
});
var infowindow = new google.maps.InfoWindow();
var latLng = new google.maps.LatLng(a, b);
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: icon,
title: c
});
infowindow.setContent(c);
infowindow.open(map, marker);
});
[my work][1][1]: https://i.stack.imgur.com/BlSuP.png

Display multiple routes on google map

I am trying to show multiple routes on google map but It is showing only one. Can you please what I am doing wrong?
<div class="searchmap" style="float:left;margin-left:1%" id="map"></div>
var map = null;
var markerPoints = [];
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById("map"), {scrollwheel:false, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, center:new google.maps.LatLng(19.0759837, 72.87765590000004), zoom:13});
directionsDisplay.setMap(map);
}
function calcRoute(flat, flng, tlat, tlng)
{
var start = new google.maps.LatLng(flat, flng);
var end = new google.maps.LatLng(tlat, tlng);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false,
suppressInfoWindows: true
});
directionsDisplay.setMap(map);
directionsService.route(request, function(result, status) {
console.log(result);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
calcRoute("19.210430", "72.843422", "19.109858", "72.878433");
calcRoute("19.228977", "72.856812", "19.117302", "72.884041");
Can you please let me know what I am doing wrong?
Display multiple routes on google map with waypoints and direction arrow
==============
Click here!
![In image u can see 2 routes with direction arrow][1]
<style>
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var directionsService;
var stepDisplay;
var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];
var stops_data = [[ {"Geometry":{"Latitude":23.05242,"Longitude":72.53375}},
{"Geometry":{"Latitude":23.03007,"Longitude":72.59664}}
] ,[ {"Geometry":{"Latitude":23.00959,"Longitude":72.56189}},
{"Geometry":{"Latitude":23.05754,"Longitude":72.55302}}
]];
var a,z,b;
var add;
var speed = 0.000005, wait = 1;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
var myPano;
var panoClient;
var nextPanoId;
var directionsDisplay = [];
directionsDisplay[0] = new window.google.maps.DirectionsRenderer({
suppressMarkers: true
});
directionsDisplay[1] = new window.google.maps.DirectionsRenderer({
suppressMarkers: true
});
var map;
var mapOptions = { center: new google.maps.LatLng(42.5584308, -70.8597732), zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize()
{
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsService = new google.maps.DirectionsService();
// Setroute(locations[0],locations[1],directionsDisplay[0]);
// Setroute(locations2[0],locations2[1],directionsDisplay[1]);
Tour_startUp(stops_data[0]);
window.tour.loadMap(map, directionsDisplay[0]);
window.tour.fitBounds(stops_data[0],map);
if (stops_data[0].length > 1)
window.tour.calcRoute(stops_data[0],directionsService, directionsDisplay[0]);
Tour_startUp(stops_data[1]);
window.tour.loadMap(map, directionsDisplay[1]);
window.tour.calcRoute(stops_data[1],directionsService, directionsDisplay[1]);
window.tour.fitBounds(stops_data[1],map);
}
function fx(o)
{
if(o && o.legs)
{
for(l=0;l<o.legs.length;l++)
{
var leg=o.legs[l];
for(var s=0;s<leg.steps.length;++s)
{
var step=leg.steps[s],
a=(step.lat_lngs.length)?step.lat_lngs[0]:step.start_point,
z=(step.lat_lngs.length)?step.lat_lngs[1]:step.end_point,
dir=((Math.atan2(z.lng()-a.lng(),z.lat()-a.lat())*180)/Math.PI)+360,
ico=((dir-(dir%3))%120);
new google.maps.Marker({
position: a,
icon: new google.maps.MarkerImage('http://maps.google.com/mapfiles/dir_'+ico+'.png',
new google.maps.Size(24,24),
new google.maps.Point(0,0),
new google.maps.Point(12,12)
),
map: map,
title: Math.round((dir>360)?dir-360:dir)+'°'
});
}
}
}
}
function Tour_startUp(stops) {
// alert('first'+stops.length);
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, dirdis) {
var myOptions = {
zoom: 15,
center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
dirdis.setMap(map);
},
fitBounds: function (stops_data,map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
for( var x in stops_data) {
var myLatlng = new window.google.maps.LatLng(stops_data[x].Geometry.Latitude, stops_data[x].Geometry.Longitude);
bounds.extend(myLatlng);
}
map.fitBounds(bounds);
},
calcRoute: function (stops_new,directionsService, dirdis) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops_new.length > 0;
var time= [];
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
// alert('second'+stops_new.length);
//alert(stops_new[0].Geometry.Latitude +' ===== ' +stops_new[0].Geometry.Longitude);
for (var j = itemsCounter; j < stops_new.length; j++) {
subitemsCounter++;
//alert(stops[j].Geometry.Time);
subBatch.push({
location: new window.google.maps.LatLng(stops_new[j].Geometry.Latitude, stops_new[j].Geometry.Longitude),
stopover: true
});
//time.push(stops[j].Geometry.Time);
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops_new.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request =
{
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
// alert('start'+start);
// alert('end'+end);
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
fx(result.routes[0]);
polyline[0] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
poly2[0] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
dirdis.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var path = combinedResults.routes[0].overview_path;
//alert(path.length);
// alert(legs.length);
//setRoutes(legs[0].start_location,legs[legs.length-1].end_location);
for (var i=0; i < legs.length;i++)
{
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
if (i == 0) {
//marker[0] = createMarker2(legs[i].start_location,"start",legs[i].start_address,"green");
}
var steps = legs[i].steps;
// alert('arrival time : '+legs[i].arrival_time.text);
// var duration = steps.duration_in_traffic;
// alert(duration.text);
for (j=0;j<steps.length;j++)
{
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++)
{
polyline[0].getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
}
}
// createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
}
// Marker for start point
createMarker(dirdis.getMap(),legs[0].start_location,"marker"+0,"Start Point<br>"+legs[0].start_address,'A');
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
// marker for End Point
createMarker(dirdis.getMap(),legs[legs.length-1].end_location,"marker"+i,"End Point <br>"+legs[legs.length-1].end_address,'B');
polyline[0].setMap(map);
//startAnimation(0);
}
}
});
})(k);
}
}
};
}
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(iconStr) {
//alert(iconStr);
if ((typeof(iconStr)=="undefined") || (iconStr==null)) {
iconStr = "red";
}
if(iconStr == 'A')
{
// for start point
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-start.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
}
}
if (iconStr == 'B')
{
// for end point
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-end.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
}
}
return icons[iconStr];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = new google.maps.MarkerImage('mapIcons/marker_red.png',
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, html, color) {
//alert(color);
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
// alert('creatMarker'+contentString);
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: iconShadow,
icon: getMarkerImage(color),
shape: iconShape,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas"></div>
[1]: http://i.stack.imgur.com/yB4Tw.png
Here you go.. the full explaination , credit goes to the author
function drawMap() {
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = new google.maps.LatLng(51.47482547819850,-0.37739553384529);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
function requestDirections(start, end) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
}
requestDirections('(51.47482547819850,-0.37739553384529)', '(51.59512428598160,-0.17190814889409)');
requestDirections('EC1V 0AH', '(51.47615506206120, -0.37795315370703)');
}
you need to create an instance of google.maps.DirectionsRenderer(); EVERYTIME you draw the route to make it visible ;)
Your directionsDisplay variable is an instance of google.maps.DirectionsRenderer() and that can only hold one set of directions at a time. If you want to display more than one route, you need multiple google.maps.DirectionsRenderer().
To get multiple routes we can add provideRouteAlternatives = true inside request object while calling route() of DirectionsService object. See Directions Requests.
This method will return array of routes if available with their name in summary key.
Now we can display these routes on view and on click of each route we can pass route object and can render the direction by setDirections() of DirectionsRenderer object. See Displaying the DirectionsResult
try this code
<!DOCTYPE html>
<html>
<head>
<title>Waypoints in Directions</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=your-key&callback=initMap&libraries=&v=weekly"
defer
></script>
<style type="text/css">
html,
body {
height: 99%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
float: left;
width: 99%;
height: 100%;
}
</style>
<script>
"use strict";
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
center: {
lat: 19.8762,
lng: 75.3433
}
});
const directionsService = new google.maps.DirectionsService();
let points = [
{
origin: {
lat: 19.9974533,
lng: 73.78980229999999
},
destination: {
lat: 19.0759837,
lng: 72.8776559
},
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
},
{
origin: {
lat: 21.1458,
lng: 79.0882
},
destination: {
lat: 18.5204,
lng: 73.8567
},
// waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}
]
for (var i = 0; i < points.length; i++) {
calculateAndDisplayRoute(directionsService,points[i])
}
function calculateAndDisplayRoute(directionsService,points) {
let directionsRenderer = new google.maps.DirectionsRenderer();
// const waypts = [{
// location: {
// lat: 19.8762,
// lng: 75.3433
// },
// },
// ];
directionsService.route(
points,
(response, status) => {
console.log(response);
if (status === "OK") {
directionsRenderer.setDirections(response);
directionsRenderer.setMap(map);
} else {
window.alert("Directions request failed due to " + status);
}
}
);
}
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>