Search code examples
javascriptjquerygoogle-mapsjquery-waypoints

How to display dynamic name in google map waypoint API


Here i am doing Google map waypoint API, it is working fine.click the submit button then map will display in this map waypoint1 & waypoint 2 is comming static instedd of this i wantg to display empName (it is JSON response). i tried like i removed waypoint static values istead of this i given value.empNAme but this not working properly it showing last name only, how can do this.

$('#btn-submit').click(function(e){
    e.preventDefault();
    var res={
        "status": "success",
        "count": 3,
        "data":
            [
                {
                    "tripId": "1",
                    "pickUpLatitidute": "12.9565226",
                    "pickUpLongitude": "77.70730989999993",
                     "empName":"Arun",
                     "stratingTime" : "9.30 AM",
                      "presentStatus" : "Yes",
                },
                {
                    "tripId": "1",
                    "pickUpLatitidute": "12.9550587",
                    "pickUpLongitude": "77.68279819999998",
                    "empName":"Sharma",
                     "stratingTime" : "9.40 AM",
                      "presentStatus" : "Yes",
                },
                {
                    "tripId": "1",
                    "pickUpLatitidute": "12.9824",
                    "pickUpLongitude": "77.6927990",
                    "empName":"Dinesh",
                     "stratingTime" : "9.50 AM",
                     "presentStatus" : "Yes",
                }
            ]
        };


        
    if(res['status']=='success'){
    for (i = 0; i < 3; i++) { 
        var waypts=[];
        $.each( res['data'], function( key, value ) {
           var map;
		   var gmarkers = [];
		   var directionsDisplay = new google.maps.DirectionsRenderer({
				suppressMarkers: true
			  });
			  var directionsService = new google.maps.DirectionsService;
			  map = new google.maps.Map(document.getElementById('map'), {
				zoom: 14,
				center: {
				  lat: 12.9577129,
				  lng: 77.6764937
				} // Starting Point Marathahalli
			  });
			  directionsDisplay.setMap(map);

			   //calculateAndDisplayRoute START HERE
			  calculateAndDisplayRoute(directionsService, directionsDisplay);
	            function calculateAndDisplayRoute(directionsService, directionsDisplay) {
	            	var selectedMode = document.getElementById('mode').value;
	                var latitdute = JSON.parse(value.pickUpLatitidute);
	                var longitude = JSON.parse(value.pickUpLongitude);
	                waypts.push(
	                    {
	                        location: {
	                            lat: latitdute,
	                            lng: longitude
	                        },
	                        stopover: true
	                    }
	                );


	                  directionsService.route({
						origin: {
						  lat: 12.9577129,
						  lng: 77.6764937
						}, // Must Need to give This is Starting Point.
						destination: {
						  lat: 12.9868068,
						  lng: 77.6070679
						}, // Must Need to give This is Ending Point.
						travelMode: google.maps.TravelMode[selectedMode],
						waypoints: waypts
					  }, function(response, status) {
						if (status == 'OK') {
						  directionsDisplay.setDirections(response);
						  RenderCustomDirections(response, status);
						} else {
						  window.alert('Directions request failed due to ' + status);
						}
					  });
	            }
	            //calculateAndDisplayRoute END HERE
	            function RenderCustomDirections(response, status) {
				  if (status == google.maps.DirectionsStatus.OK) {
					waypts = [];
					var bounds = new google.maps.LatLngBounds();
					var route = response.routes[0];
					startLocation = new Object();
					endLocation = new Object();

					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;
						startLocation.marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green", String.fromCharCode("A".charCodeAt(0)));
					  } else {
						  
						waypts[i] = new Object();
						waypts[i].latlng = legs[i].start_location;
						waypts[i].address = legs[i].start_address;
						waypts[i].marker = createMarker(legs[i].start_location, "waypoint" + i, legs[i].start_address, "yellow", String.fromCharCode("A".charCodeAt(0) + i));
						
					  }
					  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++) {
						  bounds.extend(nextSegment[k]);
						}
					  }
					}
					console.log(response);
					endLocation.marker = createMarker(endLocation.latlng, "My Company", endLocation.address, "red", String.fromCharCode("A".charCodeAt(0) + waypts.length));
					google.maps.event.trigger(endLocation.marker, 'click');
				  } else alert(status);
				}
	            var icons = new Array();
				icons["red"] = {
				  url: "http://maps.google.com/mapfiles/ms/micons/red.png",
				  // This marker is 32 pixels wide by 32 pixels tall.
				  size: new google.maps.Size(32, 32),
				  // The origin for this image is 0,0.
				  origin: new google.maps.Point(0, 0),
				  // The anchor for this image is at 9,34.
				  anchor: new google.maps.Point(16, 32),
				  labelOrigin: new google.maps.Point(16, 10)
				};

				function getMarkerImage(iconColor) {
				  if ((typeof(iconColor) == "undefined") || (iconColor == null)) {
					iconColor = "red";
				  }
				  if (!icons[iconColor]) {
					icons[iconColor] = {
					  url: "http://maps.google.com/mapfiles/ms/micons/" + iconColor + ".png",
					  // This marker is 32 pixels wide by 32 pixels tall.
					  size: new google.maps.Size(32, 32),
					  // The origin for this image is 0,0.
					  origin: new google.maps.Point(0, 0),
					  // The anchor for this image is at 6,20.
					  anchor: new google.maps.Point(16, 32),
					  labelOrigin: new google.maps.Point(16, 10)
					};
				  }
				  return icons[iconColor];

				}

				var iconImage = {
				  url: 'http://maps.google.com/mapfiles/ms/micons/red.png',
				  // This marker is 20 pixels wide by 34 pixels tall.
				  size: new google.maps.Size(20, 34),
				  // The origin for this image is 0,0.
				  origin: new google.maps.Point(0, 0),
				  // The anchor for this image is at 9,34.
				  anchor: new google.maps.Point(9, 34)
				};
				
				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'
				};
				var infowindow = new google.maps.InfoWindow({
				  size: new google.maps.Size(150, 50)
				});

				function createMarker(latlng, title, html, color, label) {
				  var contentString = '<b>' + title + '</b><br>' + html;
				  var marker = new google.maps.Marker({
					position: latlng,
					draggable: true,
					map: map,
					icon: getMarkerImage(color),
					shape: iconShape,
					title: title,
					label: label,
					zIndex: Math.round(latlng.lat() * -100000) << 5
				  });
				  marker.myname = title;
				  gmarkers.push(marker);

				  google.maps.event.addListener(marker, 'click', function() {
					infowindow.setContent(contentString);
					infowindow.open(map, marker);
				  });

				  return marker;
				}


        });
        console.log(waypts);
    }
    }
});
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Travel modes in directions</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #floating-panel {
        position: absolute;
        top: 10px;
        left: 25%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }
    </style>
  </head>
  <body>
  <form id="testForm">
  
	<select name="tripId">
		<option value="">Select trip</option>
		<option value="1">1</option>
		<option value="2">2</option>
	</select>
	
	<button type="button" id="btn-submit">submit</button>
  </form><br></br>
  
    <div id="floating-panel">
    <b>Mode of Travel: </b>
    <select id="mode">
      <option value="DRIVING">Driving</option>
    </select>
    </div>
    <div id="map"></div>
       <script
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7lDrYPDmJz1JsQh2rbWA9uRZHcFk_xJY">
    </script>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

My JSON RESPONSE

var res={
    "status": "success",
    "count": 3,
    "data":
        [
            {
                "tripId": "1",
                "pickUpLatitidute": "12.9565226",
                "pickUpLongitude": "77.70730989999993",
                 "empName":"Arun",
                 "stratingTime" : "9.30 AM",
                  "presentStatus" : "Yes",
            },
            {
                "tripId": "1",
                "pickUpLatitidute": "12.9550587",
                "pickUpLongitude": "77.68279819999998",
                "empName":"Sharma",
                 "stratingTime" : "9.40 AM",
                  "presentStatus" : "Yes",
            },
            {
                "tripId": "1",
                "pickUpLatitidute": "12.9824",
                "pickUpLongitude": "77.6927990",
                "empName":"Dinesh",
                 "stratingTime" : "9.50 AM",
                 "presentStatus" : "Yes",
            }
        ]
    };

Solution

  • You can use res.data[(i - 1)].empName in the line below.

    waypts[i].marker = createMarker(legs[i].start_location, res.data[(i - 1)].empName, legs[i].start_address, "yellow", String.fromCharCode("A".charCodeAt(0) + i));
    

    Working example below.

    $('#btn-submit').click(function(e) {
      e.preventDefault();
      var res = {
        "status": "success",
        "count": 3,
        "data": [{
            "tripId": "1",
            "pickUpLatitidute": "12.9565226",
            "pickUpLongitude": "77.70730989999993",
            "empName": "Arun",
            "stratingTime": "9.30 AM",
            "presentStatus": "Yes",
          },
          {
            "tripId": "1",
            "pickUpLatitidute": "12.9550587",
            "pickUpLongitude": "77.68279819999998",
            "empName": "Sharma",
            "stratingTime": "9.40 AM",
            "presentStatus": "Yes",
          },
          {
            "tripId": "1",
            "pickUpLatitidute": "12.9824",
            "pickUpLongitude": "77.6927990",
            "empName": "Dinesh",
            "stratingTime": "9.50 AM",
            "presentStatus": "Yes",
          }
        ]
      };
    
    
      if (res['status'] == 'success') {
        for (i = 0; i < 3; i++) {
          var waypts = [];
          $.each(res['data'], function(key, value) {
            var map;
            var gmarkers = [];
            var directionsDisplay = new google.maps.DirectionsRenderer({
              suppressMarkers: true
            });
            var directionsService = new google.maps.DirectionsService;
            map = new google.maps.Map(document.getElementById('map'), {
              zoom: 14,
              center: {
                lat: 12.9577129,
                lng: 77.6764937
              } // Starting Point Marathahalli
            });
            directionsDisplay.setMap(map);
    
            //calculateAndDisplayRoute START HERE
            calculateAndDisplayRoute(directionsService, directionsDisplay);
    
            function calculateAndDisplayRoute(directionsService, directionsDisplay) {
              var selectedMode = document.getElementById('mode').value;
              var latitdute = JSON.parse(value.pickUpLatitidute);
              var longitude = JSON.parse(value.pickUpLongitude);
              waypts.push({
                location: {
                  lat: latitdute,
                  lng: longitude
                },
                stopover: true
              });
    
    
              directionsService.route({
                origin: {
                  lat: 12.9577129,
                  lng: 77.6764937
                }, // Must Need to give This is Starting Point.
                destination: {
                  lat: 12.9868068,
                  lng: 77.6070679
                }, // Must Need to give This is Ending Point.
                travelMode: google.maps.TravelMode[selectedMode],
                waypoints: waypts
              }, function(response, status) {
                if (status == 'OK') {
                  directionsDisplay.setDirections(response);
                  RenderCustomDirections(response, status);
                } else {
                  window.alert('Directions request failed due to ' + status);
                }
              });
            }
            //calculateAndDisplayRoute END HERE
            function RenderCustomDirections(response, status) {
              if (status == google.maps.DirectionsStatus.OK) {
                waypts = [];
                var bounds = new google.maps.LatLngBounds();
                var route = response.routes[0];
                startLocation = new Object();
                endLocation = new Object();
    
                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;
                    startLocation.marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green", String.fromCharCode("A".charCodeAt(0)));
                  } else {
    
                    waypts[i] = new Object();
                    waypts[i].latlng = legs[i].start_location;
                    waypts[i].address = legs[i].start_address;
                    waypts[i].marker = createMarker(legs[i].start_location, res.data[(i - 1)].empName + " " + res.data[(i -1)].stratingTime+  " " + res.data[(i -1)].presentStatus, legs[i].start_address, "yellow", String.fromCharCode("A".charCodeAt(0) + i));
    
                  }
                  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++) {
                      bounds.extend(nextSegment[k]);
                    }
                  }
                }
                endLocation.marker = createMarker(endLocation.latlng, "My Company", endLocation.address, "red", String.fromCharCode("A".charCodeAt(0) + waypts.length));
                google.maps.event.trigger(endLocation.marker, 'click');
              } else alert(status);
            }
            var icons = new Array();
            icons["red"] = {
              url: "http://maps.google.com/mapfiles/ms/micons/red.png",
              // This marker is 32 pixels wide by 32 pixels tall.
              size: new google.maps.Size(32, 32),
              // The origin for this image is 0,0.
              origin: new google.maps.Point(0, 0),
              // The anchor for this image is at 9,34.
              anchor: new google.maps.Point(16, 32),
              labelOrigin: new google.maps.Point(16, 10)
            };
    
            function getMarkerImage(iconColor) {
              if ((typeof(iconColor) == "undefined") || (iconColor == null)) {
                iconColor = "red";
              }
              if (!icons[iconColor]) {
                icons[iconColor] = {
                  url: "http://maps.google.com/mapfiles/ms/micons/" + iconColor + ".png",
                  // This marker is 32 pixels wide by 32 pixels tall.
                  size: new google.maps.Size(32, 32),
                  // The origin for this image is 0,0.
                  origin: new google.maps.Point(0, 0),
                  // The anchor for this image is at 6,20.
                  anchor: new google.maps.Point(16, 32),
                  labelOrigin: new google.maps.Point(16, 10)
                };
              }
              return icons[iconColor];
    
            }
    
            var iconImage = {
              url: 'http://maps.google.com/mapfiles/ms/micons/red.png',
              // This marker is 20 pixels wide by 34 pixels tall.
              size: new google.maps.Size(20, 34),
              // The origin for this image is 0,0.
              origin: new google.maps.Point(0, 0),
              // The anchor for this image is at 9,34.
              anchor: new google.maps.Point(9, 34)
            };
    
            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'
            };
            var infowindow = new google.maps.InfoWindow({
              size: new google.maps.Size(150, 50)
            });
    
            function createMarker(latlng, title, html, color, label) {
              var contentString = '<b>' + title + '</b><br>' + html;
              var marker = new google.maps.Marker({
                position: latlng,
                draggable: true,
                map: map,
                icon: getMarkerImage(color),
                shape: iconShape,
                title: title,
                label: label,
                zIndex: Math.round(latlng.lat() * -100000) << 5
              });
              marker.myname = title;
              gmarkers.push(marker);
    
              google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(contentString);
                infowindow.open(map, marker);
              });
    
              return marker;
            }
    
    
          });
        }
      }
    });
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
      <meta charset="utf-8">
      <title>Travel modes in directions</title>
      <style>
        /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
        
        #map {
          height: 100%;
        }
        /* Optional: Makes the sample page fill the window. */
        
        html,
        body {
          height: 100%;
          margin: 0;
          padding: 0;
        }
        
        #floating-panel {
          position: absolute;
          top: 10px;
          left: 25%;
          z-index: 5;
          background-color: #fff;
          padding: 5px;
          border: 1px solid #999;
          text-align: center;
          font-family: 'Roboto', 'sans-serif';
          line-height: 30px;
          padding-left: 10px;
        }
      </style>
    </head>
    
    <body>
      <form id="testForm">
    
        <select name="tripId">
    		<option value="">Select trip</option>
    		<option value="1">1</option>
    		<option value="2">2</option>
    	</select>
    
        <button type="button" id="btn-submit">submit</button>
      </form><br></br>
    
      <div id="floating-panel">
        <b>Mode of Travel: </b>
        <select id="mode">
          <option value="DRIVING">Driving</option>
        </select>
      </div>
      <div id="map"></div>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7lDrYPDmJz1JsQh2rbWA9uRZHcFk_xJY">
      </script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>