I have a application where i have to plot the polylines and place some markers on the google map where in order to plot the polylines i am getting the data from the database every thing works fine but i am getting the error in developers console has
InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object; and not an Object
After trying to debug for a long time i found there is some problem in the way plot the polyline (ie some undefined value is pumbing in the array please have a look in the for loop )
for (var i = 0; i <lat_lng.length+2; i++) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
var k=i;
i=i+1;
getDirections(src, des, colorVariable[k%colorVariable.length], map);
}
this is angularjs application my complete controller is has shown below
//....map controller.........
changiControllers.controller("map", function ($scope,$http) {
$(".calendarMain .selectDay").dateSelectSlider();
$(".timeSlider").timeSlider();
$scope.jsonData=[ {
"title": 'point11',
"lat": '1.351477',
"lng": '103.985701',
"description": 'uuu'
}, {
"title": 'point12',
"lat": '1.350265',
"lng": '103.985165',
"description": 'uuu'
}];
$scope.markerData=[{
"title": 'point3',
"lat": '1.354432',
"lng": '103.987262',
"description": 'zzz'
}];
socket.on('plotData', function (dataMap) {
$scope.jsonData=[];
$scope.markerData=[];
for(var i = 0;i<dataMap.data.length;i++){
if(i==3||i==6){
$scope.markerData.push(dataMap.data[i]);
}
$scope.jsonData.push(dataMap.data[i]);
}
$scope.$apply();
$scope.laneMapInit();
});
$scope.laneMapInit=function() {
var gmarkers = [];
var colorVariable = ["yellow", "green", "red"];
var map;
var mapOptions = {
center: new google.maps.LatLng(1.35, 103.987),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: true,
draggable: true,
disableDefaultUI: false,
heading: 90,
tilt: 0,
styles: [
{
"featureType": "poi",
"stylers": [
{ "visibility": "off" }
]
}
]
};
map = new google.maps.Map(document.getElementById("laneMap"), mapOptions);
var data= $scope.jsonData;
var lat_lng = new Array();
var markerModel= $scope.markerData;
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
for ( var a = 0; a < data.length; a++) {
var myLatlng = new google.maps.LatLng(data[a].lat, data[a].lng);
lat_lng.push(myLatlng);
}
for (var j = 0; j < markerModel.length; j++) {
var myLatlngMarker = new google.maps.LatLng(markerModel[j].lat, markerModel[j].lng);
var marker = new google.maps.Marker({
position: myLatlngMarker,
map: map,
icon: {
url:'images/liveCam32.png',
},
title: markerModel[j].title
});
latlngbounds.extend(marker.position);
(function(marker, markerModel) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(markerModel.description);
infoWindow.open(map, marker);
});
})(marker, markerModel[j]);
gmarkers.push(marker);
}
map.setCenter(latlngbounds.getCenter());
for (var i = 0; i <lat_lng.length+2; i++) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
var k=i;
i=i+1;
getDirections(src, des, colorVariable[k%colorVariable.length], map);
}
function getDirections(src, des, color, map) {
//Intialize the Direction Service
var service = new google.maps.DirectionsService( {preserveViewport: true} );
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Intialize the Path Array
var path = [];
for (var i = 0; i < result.routes[0].overview_path.length; i++) {
path.push(result.routes[0].overview_path[i]);
}
//Set the Path Stroke Color
var polyOptions = {
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 8,
path: path,
map: map
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
}
});
}
};
$scope.laneMapInit();
$scope.simulateMapDraw = function(flag){
if(flag){
$scope.mapPlotIntervalId=setInterval(function() {
$http.get('http://localhost:3000/newPlotMsg').then(function(result){
});
},4000);
}else if(!flag){
clearInterval($scope.mapPlotIntervalId);
}
}
});
You are running past the end of your array. i can't be equal to or greater than lat_lng.length, change:
for (var i = 0; i <lat_lng.length+2; i++) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
var k=i;
i=i+1;
getDirections(src, des, colorVariable[k%colorVariable.length], map);
}
To:
for (var i = 0; i < lat_lng.length; i++) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
var k=i;
i=i+1;
getDirections(src, des, colorVariable[k%colorVariable.length], map);
}
proof of concept fiddle
Related
I want to make the markers of a certain type disappear depending on the scale
I achieved that all markers would be switched off at a scale of <= 14
Tell me how to correctly write a condition for disabling markers with the type "ps1" for a scale <= 14
<script>
var markerType = {
"ps1": [], "tp1": [], "rtp0": []
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(47.82034163, 31.19833049),
zoom: 14,
});
var image = {
rtp0: {
url: './image/rtp0.png',scaledSize: new google.maps.Size(28, 40)},
ps1: {
url: './image/ps1.png',scaledSize: new google.maps.Size(28, 40)},
tp1: {
url: './image/tp1.png',scaledSize: new google.maps.Size(28, 40)},
};
downloadUrl('phpsqlinfo.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var type = markerElem.getAttribute('type');
var icon = image[type] || {};
var marker = new google.maps.Marker({
icon: icon,
map: map,
position: point,
});
markerType[type].push(marker);
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomLevel = map.getZoom();
for (var i = 0; i < markerType[type].length; i++) {
var markers = markerType[type][i];
if (zoomLevel <= 14) {
(!markers.getVisible())
markers.setVisible(false);
}
else {
markers.setVisible(true);
}
}
});
});
});
}
</script>
You need to set the markers' method to setMap(null) and setMap(map) when the zoom_changed event fires.
Store the markers you want to filter e.g ps1 in a variable:
var markersToShowHide = markerType.ps1;
Then add two functions, one to show the markers and the other to hide them:
function showMarkers() {
for (var i = 0; i < markersToShowHide.length; i++) {
markersToShowHide[i].setMap(map);
}
}
function hideMarkers() {
for (var i = 0; i < markersToShowHide.length; i++) {
markersToShowHide[i].setMap(null);
}
}
Full code:
var markerType = {
"ps1": [],
"tp1": [],
"rtp0": []
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(47.82034163, 31.19833049),
zoom: 14,
});
var image = {
rtp0: {
url: './image/rtp0.png',
scaledSize: new google.maps.Size(28, 40)
},
ps1: {
url: './image/ps1.png',
scaledSize: new google.maps.Size(28, 40)
},
tp1: {
url: './image/tp1.png',
scaledSize: new google.maps.Size(28, 40)
},
};
var markersToShowHide = markerType.ps1;
function showMarkers() {
for (var i = 0; i < markersToShowHide.length; i++) {
markersToShowHide[i].setMap(map);
}
}
function hideMarkers() {
for (var i = 0; i < markersToShowHide.length; i++) {
markersToShowHide[i].setMap(null);
}
}
downloadUrl('phpsqlinfo.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var type = markerElem.getAttribute('type');
var icon = image[type] || {};
var marker = new google.maps.Marker({
icon: icon,
map: map,
position: point
});
markerType[type].push(marker);
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() <= 14) {
hideMarkers();
} else {
showMarkers();
}
});
});
});
}
I am trying to animate a polyline on top of hidden Route (with strokeWeight: 0) and animate it on this example but not sure why I am not able to grab the correct points on .interpolate() method.
What am I doing wrong?
<script src="https://maps.googleapis.com/maps/api/js?key=xxx&libraries=geometry"></script>
var map;
$(document).ready(function() {
var latlng = new google.maps.LatLng(49.241943, -122.889318);
var myOptions = {
zoom: 12,
center: latlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map_canvas').get(0), myOptions);
//Starting Direction Services
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
});
directionsService.route({
origin: new google.maps.LatLng(49.241943, -122.889318),
destination: new google.maps.LatLng(49.241943, -122.999999),
waypoints: [{
stopover: false,
location: new google.maps.LatLng(49.241943, -122.889318)
}],
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
// directionsDisplay.setDirections(response);
var polyline = new google.maps.Polyline({
path: [],
strokeColor: 'red',
strokeWeight: 0
});
var bounds = new google.maps.LatLngBounds();
var line = response.routes[0].legs;
for (i = 0; i < polyline.length; i++) {
var steps = polyline[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
var step = 0;
var numSteps = 250;
var timePerStep = 5;
var interval = setInterval(function() {
step += 1;
if (step > numSteps) {
clearInterval(interval);
} else {
var are_we_there_yet = google.maps.geometry.spherical.interpolate(line, step / numSteps);
line.setPath([polyline, are_we_there_yet]);
}
}, timePerStep);
line.setMap(map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
The interpolate function takes these three parameters, according to the docs:
from: LatLng,
to: LatLng,
fraction: number
You're passing it the following two parameters:
google.maps.geometry.spherical.interpolate(line, step / numSteps)
And instead of passing the whole line, you should do something like:
google.maps.geometry.spherical.interpolate(latLng1, latLng2, step / numSteps)
... where latLng1 and latLng2 would be the endpoints of your line I guess.
You're also doing this... you create a Polyline, polyline. Then you get a line. But you then try and loop over polyline.length:
var polyline = new google.maps.Polyline({
path: [],
strokeColor: 'red',
strokeWeight: 0
});
var line = response.routes[0].legs;
for (i = 0; i < polyline.length; i++) {
I think that last line (and other references inside the nested loops) should refer to the line not the polyline, i.e.
for (i = 0; i < line.length; i++) {
This is my first experience with GoogleMaps/JS.
My map is working as expected with individual markers. But when i add marker cluster function its not working and the best part is no errors on the console.
Below is my code. Any help would be greatly appreciated.
function CreateMap(rootElement,data,startPin,endPin){
//console.log("startPin : " + startPin);
var google = window.google;
var map;
var marker;
var posInfoWindow;
var markers = [];
var markersArray = [];
var mapElement = rootElement.querySelector('.my-map');
currPos = localStorage.currentPosition;
var currentPosition = JSON.parse(localStorage.currentPosition);
var results = JSON.parse(data);
var defaultIcon, selectedIcon, mainIcon;
function centerOnMyLocation() {
closeAllInfoWindows();
map.panTo(marker.getPosition());
posInfoWindow.open(map, marker);
}
function closeAllInfoWindows() {
if(posInfoWindow !== void 0) {
posInfoWindow.close();
}
markers.forEach(function(it) {
it.infoWindow.close();
it.marker.setIcon(defaultIcon);
});
}
function showInfoWindow(idx) {
closeAllInfoWindows();
if(map !== void 0) {
markers[idx].infoWindow.open(map, markers[idx].marker);
markers[idx].marker.setIcon(selectedIcon);
}
}
function highlightListItem(idx) {
var items = rootElement.querySelectorAll('.my-result-list-item');
[].forEach.call(items, function(it) {
it.className = it.className.replace('my-result-list-item-highlight', '');
});
items[idx].className += ' my-result-list-item-highlight';
}
function selectMarker(idx) {
showInfoWindow(idx);
highlightListItem(idx);
}
defaultIcon = {
url: "/maps/Locator_Green_Pin.png",
anchor: new google.maps.Point(0, 0),
labelOrigin: new google.maps.Point(34, 35)
};
selectedIcon = {
url: "/maps/Locator_Yellow_Pin.png",
anchor: new google.maps.Point(0, 0),
labelOrigin: new google.maps.Point(34, 35)
};
mainIcon = {
url: "/maps/Locator_Blue_Pin.png",
anchor: new google.maps.Point(0, 0)
};
var myLatlng = new google.maps.LatLng(currentPosition.latitude, currentPosition.longitude);
map = new google.maps.Map(mapElement, {
center: myLatlng,
zoom: 3,
styles: [
{
featureType: 'poi',
stylers: [{ visibility: 'off' }] // Turn off points of interest.
}, {
featureType: 'transit.station',
stylers: [{ visibility: 'off' }] // Turn off bus stations, train stations, etc.
}
],
'mapTypeId': google.maps.MapTypeId.ROADMAP,
disableDoubleClickZoom: false,
scaleControl: true
});
map.addListener('click', function() {
closeAllInfoWindows();
});
bounds = new google.maps.LatLngBounds(); // MapAutoZoom : to fit the markers on the map
//alert("working on map");
//results.forEach(function(it, idx) {
$.each(results, function(idx, it) {
//console.log("it : " + it + " , idx : "+idx);
var labelXoffset = -30;
var labelYOffset = -28; //reduce x offset to center longer labels
if (idx >= 9 && idx <= 98) {
labelXoffset = -27;
}
else if ( idx >= 99 && idx <= 998 ) {
labelXoffset = -24;
}
if(startPin<= idx && idx<= endPin){
var m = new MarkerWithLabel({
position: new google.maps.LatLng(it.Latitude, it.Longitude),
title: it.MerchantName,
animation: google.maps.Animation.DROP,
draggable: false,
map: map,
labelContent: (idx+1).toString(),
labelAnchor: new google.maps.Point(labelXoffset, labelYOffset),
icon: defaultIcon
});
m.addListener('click', function() {
if (idx !== -1) {
showInfoWindow(idx);
highlightListItem(idx);
}
});
var iw = new google.maps.InfoWindow({
content: "<div class='my-info-window'>View details</div>"
});
var obj = {
marker: m,
infoWindow: iw
};
markers.push(obj);
var latlongVal = new google.maps.LatLng(data[i].latitude, data[i].longitude);
var markerVal = new google.maps.Marker({
position: latlongVal
});
markersArray.push(markerVal);
bounds.extend(m.position);//MapAutoZoom
}
if(idx== endPin)
return false;
});
console.log(markersArray);
map.fitBounds(bounds); // MapAutoZoom : auto-zoom
map.panToBounds(bounds); // MapAutoZoom : auto-center
marker = new google.maps.Marker({
position: myLatlng,
title: "Me",
animation: google.maps.Animation.DROP,
icon: mainIcon
});
marker.setMap(map);
posInfoWindow = new google.maps.InfoWindow({
content: "My current location"
});
marker.addListener('click', function() {
showInfoWindow(posInfoWindow, marker, map);
});
//
// Custom Current Position Control
//
var centerControlDiv = document.createElement('div');
var div = document.createElement('div');
div.id = 'goToMeUI';
div.className = 'my-map-current-position-control-container';
div.title = 'Click to show your current position';
centerControlDiv.appendChild(div);
centerControlDiv.index = 1;
var img = document.createElement('img');
img.src = '/maps/Locator_Blue_Pin.svg';
div.appendChild(img);
div.addEventListener('click', centerOnMyLocation);
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerControlDiv);
//
// List item click event handling
//
$( '.my-result-list-item', rootElement ).on('click', function(event) {
//alert("map result clicked");
selectMarker(event.currentTarget.getAttribute('data-map-list-index'));
});
function initialize(){
var markerCluster = new MarkerClusterer(map, markersArray, {imagePath: '/maps/cluster/m'});
}
google.maps.event.addDomListener(window, 'load', initialize);
}
Please click here for screen shot I have Google map which shows the relation between locations based on a condition. What I need is to draw lines from one marker to all other markers and open info windows of each marker for marker click. Can anybody suggest the way to perform the task?
var Markerss = {};
var linearray = [];
function initialize() {
var markers = [{ 'lat': '32.803', 'lon': '-96.7699', 'ExpertsCount': 2, 'Type': 'ofsite' }, { 'lat': '44.9542', 'lon': '-93.1139', 'ExpertsCount': 3, 'Type': 'onsite' }, { 'lat': '32.903', 'lon': '-150.0011', 'ExpertsCount': 5, 'Type': 'offsite' }, { 'lat': '61.85', 'lon': '-97.6501', 'ExpertsCount': 9, 'Type': 'onnsite' }];
var mapProp = {
center: new google.maps.LatLng(28.067768, 2.150065),
zoom: 5,
mapTypeId: 'terrain'
};
//var infowindow = new google.maps.InfoWindow({
// content: "Hello World!"
//});
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var icon = "";
for (i = 0; i <= markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lon));
if (data.Type == "offsite") {
icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
}
else if (data.Type == "onsite") {
icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
}
else {
icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
}
var div = document.createElement('DIV');
div.innerHTML = '<div class="mapicon" id="dvIcon" style="background-image: url(images/mapiconsmall.png);" onmouseover="javascript:$(this).next().show()" onmouseout="javascript:$(this).next().hide()" ><div class="maindiv"style="width:24px;margin-top:3px; text-align:center;margin-left:1px;"><span style="font-weight:bolder;font-size:11px;"> ' + data.ExpertsCount + '</span></div></div><div id="dvExpName" style="display:none;z-index:1;position:absolute;">' + data.expName + '</div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: i,
content: div,
flat: true,
anchor: RichMarkerPosition.MIDDLE,
icon: icon
});
Markerss[i] = marker;
//if (data.Type == "onsite") {
// Marker[i].setClickable = false;
//}
//else {
// Marker[i].setClickable = true;
//}
// Attaching a click event to the current marker
if (markers[i].Type != "onsite") {
google.maps.event.addListener(marker, 'click', function (event) {
if (linearray.length != 0)
{
for (i = 0; i < linearray.length; i++) {
linearray[i].setMap(null);
}
}
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
strokeColor: 'red'
};
for (j = 0; j < markers.length; j++) {
var marker = markers[j];
var lat = parseFloat(markers[j].lat);
var lon = parseFloat(markers[j].lon);
if (lat != event.latLng.lat()) {
var line = new google.maps.Polyline({
path: [{ lat: event.latLng.lat(), lng: event.latLng.lng() }, { lat: lat, lng: lon }],
icons: [{
icon: lineSymbol,
offset: '100%'
}],
strokeColor: 'red',
map: map
});
linearray.push(line);
}
var infoWindow = new google.maps.InfoWindow({
content: '<b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/><b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/>'
});
infoWindow.open(map, Markerss[j]);
}
});
}
}
}
Hi. I have a question about polygons in Google maps v3. How to put them under the street's layer in Google maps API v3?
This is my map: http://gidzior.net/map/ As you can see, the darker area is above the streets. Is there a way to put it under the streets?
Google maps script:
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var position;
var marker = null;
var polyline = null;
var poly2 = null;
var speed = 0.0000005, wait = 1;
var infowindow = null;
var zoomed;
var zoomedd;
var zoomeddd;
var step = 50; // 5; // metres
var myPano;
var panoClient;
var nextPanoId;
var timerHandle = null;
var size = new google.maps.Size(26,25);
var start_point = new google.maps.Point(0,0);
var foothold = new google.maps.Point(13,15);
var car_icon = new google.maps.MarkerImage("http://fama.net.pl/echo/www/img/map/car.png", size, start_point, foothold);
var size2 = new google.maps.Size(87,87);
var start_point2 = new google.maps.Point(0,0);
var foothold2 = new google.maps.Point(43,87);
var endIcon = new google.maps.MarkerImage("http://fama.net.pl/echo/www/img/map/end.png", size2, start_point2, foothold2);
function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: car_icon,
clickable: false,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
return marker;
}
function createEndMarker(latlng, label, html) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: endIcon,
clickable: false,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
return marker;
}
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService();
var pinkParksStyles = [ { featureType: "road", stylers: [ { lightness: 100 } ] },{ featureType: "landscape", elementType: "geometry", stylers: [ { hue: "#0091ff" }, { saturation: 42 }, { lightness: -44 } ] },{ featureType: "landscape", stylers: [ { visibility: "off" }, { saturation: 32 } ] },{ featureType: "transit", stylers: [ { lightness: 100 } ] },{ featureType: "road.local", stylers: [ { visibility: "simplified" } ] },{ featureType: "poi", stylers: [ { visibility: "off" } ] },{ featureType: "road", elementType: "labels", stylers: [ { visibility: "off" } ] },{ } ]
var pinkMapType = new google.maps.StyledMapType(pinkParksStyles,
{name: "Mapa Echo"});
// Create a map and center it on Warszawa.
var myOptions = {
zoom: 12,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'pink_parks']
},
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
}
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.mapTypes.set('pink_parks', pinkMapType);
map.setMapTypeId('pink_parks');
var myCoordinates = [
new google.maps.LatLng(52.179774,21.022171),
new google.maps.LatLng(52.182773,21.023030),
new google.maps.LatLng(52.186562,21.024403),
new google.maps.LatLng(52.194324,21.023974),
new google.maps.LatLng(52.200111,21.023416),
new google.maps.LatLng(52.205423,21.022558),
new google.maps.LatLng(52.211498,21.020069),
new google.maps.LatLng(52.217152,21.016807),
new google.maps.LatLng(52.216915,21.015691),
new google.maps.LatLng(52.216810,21.014747),
new google.maps.LatLng(52.216968,21.011657),
new google.maps.LatLng(52.217125,21.008868),
new google.maps.LatLng(52.216968,21.004748),
new google.maps.LatLng(52.216231,20.990543),
new google.maps.LatLng(52.214864,20.988998),
new google.maps.LatLng(52.213497,20.988955),
new google.maps.LatLng(52.211604,20.988740),
new google.maps.LatLng(52.202793,20.985736),
new google.maps.LatLng(52.194008,20.982732),
new google.maps.LatLng(52.198190,20.984191),
new google.maps.LatLng(52.193061,20.982432),
new google.maps.LatLng(52.192035,20.984964),
new google.maps.LatLng(52.190562,20.986423),
new google.maps.LatLng(52.187220,20.986938),
new google.maps.LatLng(52.171747,20.987367),
new google.maps.LatLng(52.166167,21.016979),
new google.maps.LatLng(52.179774,21.022171)
];
var polyOptions = new google.maps.Polygon({
path: myCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 0,
strokeWeight: 3,
fillColor: "#005f8c",
fillOpacity: 0.5
});
var it = new google.maps.Polyline(polyOptions);
it.setMap(map);
address = 'warszawa'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map,
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
}
var steps = []
function calcRoute(){
if (timerHandle) { clearTimeout(timerHandle); }
if (marker) { marker.setMap(null);}
polyline.setMap(null);
poly2.setMap(null);
directionsDisplay.setMap(null);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map,
suppressMarkers:true,
polylineOptions:{strokeColor:'#96C11F'}
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode,
waypoints: [{
location:new google.maps.LatLng(52.185570, 20.997255),
stopover:false}],
optimizeWaypoints: false
};
// Route the directions and pass the response to a
// function to create markers for each step.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation = new Object();
endLocation = new Object();
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
//marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
document.getElementById("distance").innerHTML = (polyline.Distance()/1000).toFixed(2)+" km";
map.fitBounds(bounds);
createEndMarker(endLocation.latlng,"end",endLocation.address,"red");
map.setZoom(18);
startAnimation();
zoomed=false;
zoomedd=false;
zoomeddd=false;
step = 50;
}
});
}
var tick = 100; // milliseconds
var eol;
var k=0;
var stepnum=0;
var speed = "";
var lastVertex = 1;
//=============== animation functions ======================
function updatePoly(d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2.getPath().getLength() > 20) {
poly2=new google.maps.Polyline([polyline.getPath().getAt(lastVertex-1)]);
// map.addOverlay(poly2)
}
if (polyline.GetIndexAtDistance(d) < lastVertex+2) {
if (poly2.getPath().getLength()>1) {
poly2.getPath().removeAt(poly2.getPath().getLength()-1)
}
poly2.getPath().insertAt(poly2.getPath().getLength(),polyline.GetPointAtDistance(d));
} else {
poly2.getPath().insertAt(poly2.getPath().getLength(),endLocation.latlng);
}
}
function animate(d) {
// alert("animate("+d+")");
if (d>eol) {;
map.panTo(endLocation.latlng);
marker.setPosition(endLocation.latlng);
return;
}
if (d>eol-20000 && zoomeddd!=true) {
map.setZoom(12); // or whatever value
zoomeddd=true;
}
if (d>eol-10000 && zoomedd!=true) {
map.setZoom(13); // or whatever value
zoomedd=true;
}
if (d>eol-1500 && zoomed!=true) {
map.setZoom(15); // or whatever value
step = 15;
zoomed=true;
}
var p = polyline.GetPointAtDistance(d);
map.panTo(p);
marker.setPosition(p);
updatePoly(d);
timerHandle = setTimeout("animate("+(d+step)+")", tick);
}
function startAnimation() {
eol=polyline.Distance();
map.setCenter(polyline.getPath().getAt(0));
// map.addOverlay(new google.maps.Marker(polyline.getAt(0),G_START_ICON));
// map.addOverlay(new GMarker(polyline.getVertex(polyline.getVertexCount()-1),G_END_ICON));
// map.addOverlay(marker);
poly2 = new google.maps.Polyline({path: [polyline.getPath().getAt(0)], strokeColor:"#0000FF", strokeWeight:10});
// map.addOverlay(poly2);
setTimeout("animate(50)",2000); // Allow time for the initial map display
}
I know this isn't the answer you were hoping for, but there is no direct way to do this using the out-of-the-box API provided overlays, such as: Circle, GroundOverlay, InfoWindow, Marker, Polygon, or Polyline. There are even limitations within this group of overlays. For example, there is no way to have a Polyline appear above a Marker. If you would like to see some changes in the way this works, your only option right now is to make an enhancement request at: gmaps-api-issues.
As an aside, I think that adding content beneath the road markings would tend to make it appear that it was actually part of the Google Maps content, rather than something custom that has been added, and more than likely leading to confusion.