straight line is coming along with road map in google map API - google-maps

I have one query regarding google map api .
I am drawing road map line between two Geo location(Suppose A and B) through one Geo point (Suppose C).
Problem is : First time when map is loaded there is always one straight line between point A and point B along with road map among these three points (A , B and C). But when map is reloaded again then straight line (Between A and B) vanishes as expected.
Could you please help me in this regard. My code is following.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Alibaug',
"lat": '28.4700',
"lng": '77.0300',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}
,
{
"title": 'Mumbai',
"lat": '28.6139',
"lng": '77.2090',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}
,
{
"title": 'Pune',
"lat": '28.5700',
"lng": '77.3200',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng[i]=myLatlng;
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
});
latlngbounds.extend(marker.position);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
} } );
} } }
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>

Only send a single request. The Google Maps Directions Service supports waypoints if you have less than 10 total points (with the free API, 25 total points with Google Maps for Business), you can use a single request, with a source, a destination and a waypoint, which will reduce the load on Google servers and make the response more consistent.
One possible reason for the behavior you are seeing is the asynchronous behavior of the Directions Service. If the responses come back in a different order than they are sent, you could see the behavior you are describing.
proof of concept fiddle
code snippet:
window.onload = function() {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = [];
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng[i] = myLatlng;
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
latlngbounds.extend(marker.position);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({
map: map,
strokeColor: '#4986E7'
});
//Loop and Draw Path Route between the Points on MAP
var request = {
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
for (var i = 0; i < lat_lng.length; i++) {
if (i == 0) {
request.origin = lat_lng[i];
} else if (i == lat_lng.length - 1) {
request.destination = lat_lng[i];
} else {
if (!request.waypoints) {
request.waypoints = [];
}
request.waypoints.push({
location: lat_lng[i]
});
}
}
service.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
poly.setPath(path);
}
});
};
var markers = [{
"title": 'Alibaug',
"lat": '28.4700',
"lng": '77.0300',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
"title": 'Mumbai',
"lat": '28.6139',
"lng": '77.2090',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}, {
"title": 'Pune',
"lat": '28.5700',
"lng": '77.3200',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
];
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="dvMap" style="width: 500px; height: 500px">

Related

google map api remove straight lines [duplicate]

This question already has an answer here:
An issue while showing a path on Google Maps
(1 answer)
Closed 6 years ago.
I'm developing a MVC app using google map API.
There are 4 or more coordinates in my program. According to that I need to draw road path. This is my code so far.
<div id="dvMap" style="width: 500px; height: 500px">
</div>
#section scripts
{
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBZxYACsC1qz9gticRd4mbki9Tes9qexdw&sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Canberra',
"lat": '-35.2809',
"lng": '149.1300',
"description": ''
},
{
"title": 'Sydny',
"lat": '-33.8688',
"lng": '151.2093',
"description": ''
},
{
"title": 'Tamworth',
"lat": '-31.0927',
"lng": '150.9320',
"description": ''
}
,
{
"title": 'Brisbane',
"lat": '-27.465895',
"lng": '153.019519',
"description": ''
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log('len ' + result.routes[0].overview_path.length)
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
</script>
}
The problem is the map is shown straight lines as well.
I need to remove straight lines from the map (should keep lines draw on road path) and what's wrong in my code? In addition, Markers should show only for starting point and destination point. But all points are shown as markers. So how to do it...? Please give me a direction for doing it....
At the beginning of your script you're drawing markers on the map. To avoid that comment out the line map: map,
var marker = new google.maps.Marker({
position: myLatlng,
// map: map,
title: data.title
});
To remove the straight lines from the map:
comment out the line
//poly.setPath(path);
You need to use a DirectionsRenderer to show routes on the map once the routes are returned by the directionsService.
Define a function to render the computed routes
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
};
Add the rendering to the callback function of the directionsService
directionsService.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
// if route is computed successfully, render it on map
if (status == google.maps.DirectionsStatus.OK) {
console.log('len ' + result.routes[0].overview_path.length);
renderDirections(result);
} else {
console.log("Error: ", status);
}
});
The issue here is that you're trying to display multiple routes on your map, check this question for details.
Hope this helps.

How to find the exact location details from latitude and longitude?

I tried using Google Maps API for 'Reverse Geocoding' to get the location by providing latitude and longitude. This gives the street address, city and country info. But I need to get the exact details like building name, shop name etc. For example, while querying the co-ordinates "72.9011206,19.0517508", Google Maps API gives "Plot No 5, VN Purav Marg, Borla, Union Park, Chembur, Mumbai, Maharashtra 400071, India". But I need to get the name of the shop "Barista Lavazza" as available in 'Google Earth' for the same co-ordinate details.
One option would be to use the Google Maps Javscript API Places library nearbySearch, search the returned results for the closest result to the requested position.
proof of concept fiddle
code snippet:
var map;
var infowindow;
var searchLoc = new google.maps.LatLng(19.0517508, 72.9011206);
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: searchLoc,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
var request = {
location: searchLoc,
radius: '50'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var distMin = Number.MAX_VALUE;
var idxMin = -1;
for (var i = 0; i < results.length; i++) {
var place = results[i];
bounds.extend(results[i].geometry.location);
var distance = google.maps.geometry.spherical.computeDistanceBetween(results[i].geometry.location, searchLoc);
if (distance < distMin) {
distMin = distance;
idxMin = i;
}
}
var marker = createMarker(results[idxMin]);
google.maps.event.trigger(marker, 'click');
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<h2 style='color:blue'>"+place.name + "</h2><br>" + place.vicinity + "<br>" + marker.getPosition().toUrlValue(7));
infowindow.open(map, this);
});
return marker;
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<div id="map_canvas"></div>

InvalidValueError: in property origin: not a string in google map

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

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>

How to display multiple markers with different icons in Google Maps V3

I am parsing a XML file for the data to place the markers. I currently have the locations plotted using a single image. What I am trying to do is set a different color marker based on a vaule from the XML file. Here is an example of the XML file.
<fatalities>
<fatalities yrnum="1" date="2013-01-30" dt="Jan. 30, 2013" time="10:12:00" tz="CST" location="BARTOW" st="GA" deaths="1" intor="1" insvr="0" nrsvr="0" nowatch="0" watch="WT0019" ef="3" h="0" m="1" o="0" p="0" v="0" unk="0" slat="34.342" slon="-84.9527" elat="34.5981" elon="-84.7313"/>
<fatalities yrnum="2" date="2013-02-21" dt="Feb. 21, 2013" time="13:10:00" tz="CST" location="SABINE" st="TX" deaths="1" intor="0" insvr="0" nrsvr="0" nowatch="1" watch="NONE" ef="1" h="0" m="1" o="0" p="0" v="0" unk="0" slat="31.32" slon="-93.97" elat="31.32" elon="-93.98"/>
<fatalities yrnum="3" date="2013-04-11" dt="Apr. 11, 2013" time="10:38:00" tz="CST" location="KEMPER" st="MS" deaths="1" intor="0" insvr="0" nrsvr="0" nowatch="1" watch="NONE" ef="3" h="0" m="0" o="0" p="1" v="0" unk="0" slat="32.63" slon="-88.88" elat="33.42" elon="-88.20"/>
<summary STATE="GA" FATALITIES="1"/>
<summary STATE="MS" FATALITIES="1"/>
<summary STATE="TX" FATALITIES="1"/>
<csummary H="0" M="2" O="0" P="1" V="0" UNK="0"/>
<total TOTAL="3"/>
</fatalities>
The value is ef in the XML file to determine which maker to place at the location. I haven't used Google Maps in years but I have been re-learning it the past couple of weeks and I have been going through many examples and search the web for answers and I really haven't found anything.
Here is a link to the test page I have set up.The markers I need to use are at the bottom. I can plot the locations using a single marker but once I try to use different markers based off the ef value from the XML I get nothing. So bascially I need to plot all markers by location. Depending on the ef value in the XML it needs to be a certain color marker.
http://www.mesquiteweather.net/xml/googlemapkt.html
Here is the code I have for this.
<script type="text/javascript">
var infowindow;
var map;
// start here
var summary_html = "";
var csummary_html = "";
var total_html = "";
var gmarkers = [];
var i = 0;
var j = 0;
var thisurl = '2013.xml';
function initialize() {
var myLatlng = new google.maps.LatLng(32.775833, -96.796667);
var myOptions = {
panControl: false,
zoom: 4,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function MyLogoControl(controlDiv) {
controlDiv.style.padding = '5px';
var logo = document.createElement('IMG');
logo.src = 'http://www.mesquiteweather.net/images/watermark_MW_GMap.png';
logo.style.cursor = 'pointer';
controlDiv.appendChild(logo);
google.maps.event.addDomListener(logo, 'click', function() {
window.location = 'http://www.mesquiteweather.net';
});
}
var logoControlDiv = document.createElement('DIV');
var logoControl = new MyLogoControl(logoControlDiv);
logoControlDiv.index = 0; // used for ordering
map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv);
downloadUrl(thisurl, function(data) {
var xml = GXml.parse(data);
var markers = data.documentElement.getElementsByTagName("fatalities");
for (var i = 0; i < markers.length; i++) {
var yrnum = markers[i].getAttribute("yrnum");
var dt = markers[i].getAttribute("dt");
var tm = markers[i].getAttribute("time");
var ef = markers[i].getAttribute("ef");
var st = markers[i].getAttribute("st");
var loc = markers[i].getAttribute("location");
var watch = markers[i].getAttribute("watch");
var dead = markers[i].getAttribute("deaths");
var h = markers[i].getAttribute("h");
var m = markers[i].getAttribute("m");
var o = markers[i].getAttribute("o");
var v = markers[i].getAttribute("v");
var p = markers[i].getAttribute("p");
var unk = markers[i].getAttribute("unk");
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("slat")),
parseFloat(markers[i].getAttribute("slon")));
var epoint = new google.maps.LatLng(parseFloat(markers[i].getAttribute("elat")),
parseFloat(markers[i].getAttribute("elon")));
var marker = createMarker(point, yrnum, dt, ef, tm, dead, h, m, o, v, p, unk, loc, st, watch);
marker.setMap(map);
var polyline = new google.maps.Polyline({
path: [point, epoint],
strokeColor: lineColor[ef],
strokeOpacity: 0.8,
strokeWeight: 2
});
polyline.setMap(map);
}
});
}
var customIcons = {
"-1": "/images/icons/mm_1_white.png",
"0": "/images/icons/mm_20_white.png",
"1": "/images/icons/mm_20_orange.png",
"2": "/images/icons/mm_20_green.png",
"3": "/images/icons/mm_20_blue.png",
"4": "/images/icons/mm_20_red.png",
"5": "/images/icons/mm_20_black.png"
};
var lineColor = {
"-1": "#FFFFFF",
"0": "#FFFFFF",
"1": "#FFA500",
"2": "#008000",
"3": "#0000FF",
"4": "#FF0000",
"5": "#000000"
};
function createMarker(point, yrnum, dt, ef, tm, dead, h, m, o, v, p, unk, loc, st, watch) {
var marker = new google.maps.Marker({position: point, icon: customIcons[ef]});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: location});
infowindow.open(map, marker);
});
return marker;
}
</script>
Any help or suggestions would be great!
-Thanks!
First thing, this is not really a problem but is improper: change var logoControl = new MyLogoControl(logoControlDiv); to var logoControl = MyLogoControl(logoControlDiv); as there is no need for the 'new' keyword there as MyLogoControl does not return a new object.
Now, below there (on the test page you have linked to here) you have to remove the following:
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
as you already have map defined earlier using myOptions and mapOptions is not defined.
Then, the first line within your downloadUrl function, remove this:
var xml = GXml.parse(data);
as it is not needed. Those are the main issues there which I noted. I should also note that your createXmlHttpRequest() function is improper as it first checks for the existence of window.ActiveXObject and that should be avoided as XMLHttpRequest() is now more prevalent and standard and should be used wherever available including in IE7+. So, I recommend changing your createXmlHttpRequest() function to the following:
function createXmlHttpRequest() {
var xhr = null;
try{//Mozilla, Safari, IE 7+...
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/xml');
}
} catch(e) {// IE 6, use only Msxml2.XMLHTTP.(6 or 3).0,
//see: http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}catch(e){
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}catch(e){}
}
}
return xhr;
}
Then, one other thing I note is that this looks incorrect:
infowindow = new google.maps.InfoWindow({content: location});
I believe instead of {content: location} you want {content: loc}