1

Map code starts from here. I'm working locally now, polyline and animation I can adjust later. Slider has two variables, so I want marker of the slider range. I was trying something with onchange function but I don't know how I can again fetch the downloadurl.

var en = 'http://localhost/path/endI';
var bus = 'http://localhost/path/mark2';
var st = 'http://localhost/path/startI';
var map;
var infoWindow;
var markerArray = [];
function load() {
    if(map == null) {
        map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(28.43427966, 77.04600334),
            zoom: 17,
            mapTypeId: 'roadmap',
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                position: google.maps.ControlPosition.TOP_CENTER
            },
            zoomControl: true,
            zoomControlOptions: {
                position: google.maps.ControlPosition.LEFT_CENTER
            },
            scaleControl: true,
            streetViewControl: false,
            fullscreenControl: true,
            fullscreenControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            }

        });
        infoWindow = new google.maps.InfoWindow ({ maxWidth: 200 });

        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map);
        var images = 'http://localhost/path/office.png';
        var beachMarker = new google.maps.Marker({
            position: {lat: 28.4136, lng:77.0420},
            map: map,
            icon: images
    });

    }
       //here i call my xml file which contains lat lang sync time and all 

        downloadUrl("http://localhost/path/vehicle.php.xml", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for(var j = 0; j < markerArray.length; j++) {
            markerArray[j].setMap(null);
        }
        markerArray = [];           

        for (var i = 0; i < markers.length; i++) {

        var point = new google.maps.LatLng(
                        parseFloat(markers[i].getAttribute("lat")),
                        parseFloat(markers[i].getAttribute("lng")));
            var name = markers[i].getAttribute("name");

            var sync_time = markers[i].getAttribute("sync_time");
            var loc = markers[i].getAttribute("location");
            var vehicleNum = markers[i].getAttribute("vehicleNo");
            var busIcon = bus + ".png";
            var startIcon = st + ".png";
            var endIcon = en + ".png";
            if(i == 0){
                var marker = new google.maps.Marker({
                        map: map,
                        position: point,
                        icon: startIcon 
                    });
                    map.panTo(marker.getPosition());  
            markerArray.push(marker);

            var html = '<h1 style="color:green; font-weight:bold; text-align:center;">Trip Started From Here</h1><br>'+'<div style="height:90px;">' + '<b>Route ' + name + '</b><br /><b>Bus Number</b>: ' + vehicleNum + '<br /><b>Location</b>: ' + loc + '<br /><b>Start Time</b>: ' + sync_time + '</div>';
            bindInfoWindow(marker, map, infoWindow, html);
            }
            if(i == markers.length-1){
                var marker = new google.maps.Marker({
                        map: map,
                        position: point,
                        icon: endIcon 
                    });
                    map.panTo(marker.getPosition());  
                    markerArray.push(marker);

            var html = '<h1 style="color:red; font-weight:bold;text-align:center;">Trip Ends Here</h1><br>'+'<div style="height:90px;">' + '<b>Route ' + name + '</b><br /><b>Bus Number</b>: ' + vehicleNum + '<br /><b>Location</b>: ' + loc + '<br /><b>End Time</b>: ' + sync_time + '</div>';
            bindInfoWindow(marker, map, infoWindow, html);
            }
            var marker = new google.maps.Marker({
                        map: map,
                        position: point,
                        icon: busIcon 
                    });
            map.panTo(marker.getPosition());  
            markerArray.push(marker);

            var html = '<div style="height:90px;">' + '<b>Route ' + name + '</b><br /><b>Bus Number</b>: ' + vehicleNum + '<br /><b>Location</b>: ' + loc + '<br /><b>Sync Time</b>: ' + sync_time + '</div>';
            bindInfoWindow(marker, map, infoWindow, html);

            if(i>1){
                var iconsetngs = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
                var latlng1 = marker.getPosition();
                var latlng2 = markerArray[i-1].getPosition();
                var flightPlanCoordinates = [ latlng1,latlng2];
                var flightPath = new google.maps.Polyline({
                    path: flightPlanCoordinates,
                    strokeColor:'#dc143c',
    strokeOpacity: 0.8,
    strokeWeight: 1,
    animation: google.maps.Animation.DROP,
    map: map,
    icons: [{
        icon: iconsetngs,
        repeat:'290px',
        offset: '100%'}]
                });
        flightPath.setMap(map);

    var flightPathShadow = new google.maps.Polyline({
    path: flightPlanCoordinates,
    strokeColor: 'black',
    strokeOpacity: 0.1,
    strokeWeight: 8
  });
        flightPathShadow.setMap(map);
}
}
});
}
      function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
    });
}

function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
                new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
        }
    };

    request.open('GET', url, true);
    request.timeout = 10000;
    request.send(null);
}

function doNothing() {}

 <script src='https://code.jquery.com/jquery-1.12.4.js'></script>
 <script src='https://code.jquery.com/ui/1.12.1/jquery-ui.js'></script>

   slider have two variable , so i want marker of the slider range
   i was trying somthing with onchnage function but i dont know how i can again fetch the downloadurl 

$("#slider-range").slider({
range: true,
min: 0,
max: 1440,
step: 15,
values: [0, 1440],
slide: function (e, ui) {
var hours1 = Math.floor(ui.values[0] / 60);
    var minutes1 = ui.values[0] - (hours1 * 60);
    if (hours1.length == 1) hours1 = '0' + hours1;
    if (minutes1.length == 1) minutes1 = '0' + minutes1;
    if (minutes1 == 0) minutes1 = '00';
    if (hours1 >= 12) {
        if (hours1 == 12) {
            hours1 = hours1;
            minutes1 = minutes1 + " PM";
        } else {
            hours1 = hours1 - 12;
            minutes1 = minutes1 + " PM";
        }
    } else {
        hours1 = hours1;
        minutes1 = minutes1 + " AM";
    }
    if (hours1 == 0) {
        hours1 = 12;
        minutes1 = minutes1;
    }
    } 
    $('.slider-time').html(hours1 + ':' + minutes1);

     var hours2 = Math.floor(ui.values[1] / 60);
     var minutes2 = ui.values[1] - (hours2 * 60);

     if (hours2.length == 1) hours2 = '0' + hours2;
     if (minutes2.length == 1) minutes2 = '0' + minutes2;
     if (minutes2 == 0) minutes2 = '00';
     if (hours2 >= 12) {
        if (hours2 == 12) {
            hours2 = hours2;
            minutes2 = minutes2 + " PM";
        } else if (hours2 == 24) {
            hours2 = 11;
            minutes2 = "59 PM";
        } else {
            hours2 = hours2 - 12;
            minutes2 = minutes2 + " PM";
        }
     } else {
        hours2 = hours2;
        minutes2 = minutes2 + " AM";
     }

      $('.slider-time2').html(hours2 + ':' + minutes2);
  }
 });

All I want as I move my slider it gets value of markers and show the markers my xml file contains sync time. This is my xml file. Its not actually like this, its formatted but these are the attributes. The slider function gets xml file sync time so with this sync time and slider time it shows correct markers or path on google map.

    [lat="28.41381473" lng="77.04298833" name="01" location=""   sync_time="2016-10-12 15:58:05" vehicleNo="Abhishek"]

Please help me out.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    That xlm, does it constantly change, so it's needed to reload it constantly; or could you just load the whole xml, store the values... (or something in between...? )? Obviously in the second case all will run smoother. – Emmanuel Delay Oct 21 '16 at 09:35
  • In xml there are many latitudes , longitudes and time. these are the longitude and latitude of a vehicle. All i want to so as i move my slider(it contains a time range) markers or polyline must appear of that time – Sid Jaiswal Oct 21 '16 at 11:28

1 Answers1

0

try this

you nee date.js, at https://code.google.com/archive/p/datejs/downloads

So I translate the time into unix seconds, this makes for nice integers. I just set the min and max of the slider to the min and max unix seconds.

swap your google api key

<!DOCTYPE html>
<html>
  <head>
    <title>show markers on change of slider in google map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
  </head>
  <body>
    <script>
      // @see http://stackoverflow.com/questions/40172046/show-markers-on-change-of-slider-in-google-map
    </script>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 80%;
      }
      #slider {
        width: 50%;
        margin: 10px;
      }
    </style>
    <div id="slider"></div>
    <div id="map"></div>
    <script src="date.js" async defer></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://maps.google.com/maps/api/js?callback=initMap&key=AIzaSyAxYGlluHcsgR2X9SPX0nATQYRDeJE4u9U&libraries=geometry" async defer></script>
    <script>
      var map;
      var marker;
      var startMarker;
      var endMarker;
      var pointer = 0;  // will be the pointer of the slider
      var pointerIndex = 0;  // will be the index of the selected location
      var sliderIndex = -1; 
      var my_data = [];

      // date.js, @see http://stackoverflow.com/questions/1791895/converting-date-and-time-to-unix-timestamp 
      // download date.js at https://code.google.com/archive/p/datejs/downloads
      function getTime(timestring) {
        //timestring = "2016-10-27 14:18:00";
        var unixtime = Date.parse(timestring).getTime()/1000;
        return(unixtime);
      }
      function loadData(onReady) {
        $.ajax({
          url: 'data.json',
          dataType: 'json',
          success: function(data) {
            my_data = data;
            if(typeof onReady == 'function') {
              onReady(data);
            }
          }
        });
      }
      function generateMarkers() {
        //we only show 1 marker
        var position = {lat: Number(my_data[0].lat), lng: Number(my_data[0].lng)};
        startMarker = new google.maps.Marker({
          position: position,
          title: my_data[0].name,
          icon: {
            url: 'http://download.seaicons.com/icons/custom-icon-design/flatastic-9/32/Start-icon.png',
            size: new google.maps.Size(32, 32)
          },
          map: map
        });
        var endPosition = {lat: Number(my_data[my_data.length - 1].lat), lng: Number(my_data[my_data.length - 1].lng)};
        endMarker = new google.maps.Marker({
          position: endPosition,
          title: my_data[my_data.length - 1].name,
          icon: {
            url: 'http://megaicons.net/static/img/icons_title/320/823/title/flag-finish-icon.png',
            size: new google.maps.Size(32, 32)
          },
          map: map
        });
        // let's do this marker last, so it's on top of z-index
        marker = new google.maps.Marker({
          position: position,
          title: my_data[0].name,
          map: map
        });
        // click event, click on marker opens the infoWindow
        google.maps.event.addListener(marker, 'click', function(e) {
          var i = pointerIndex; 
          // infowindow
          var position = {lat: Number(my_data[i].lat), lng: Number(my_data[i].lng)};
          var infowindow = new google.maps.InfoWindow({
            content: my_data[i].name +'  <br/>  '+ my_data[i].sync_time,  // add what ever
            map: map,
            position: position
          }); 
        });
      }

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 28.41381473, lng: 77.04298833},
          zoom: 14
        });
        loadData(function() {
          // when the data is loaded, this callback will be called
            // set the slider
            var items = my_data.length;
            // get times
            var times = [];  // store the unix seconds in an array
            for(var i in my_data) {
              if(my_data[i].sync_time) {
                var time = getTime(my_data[i].sync_time);
                times.push(time);
              }
            }
            $('#slider').slider({
              min: times.min(),
              max: times.max(),
              slide: function( event, ui ) {
                pointer = ui.value;
                for(var i in my_data) {
                  if(my_data[i].sync_time) {
                    var time = getTime(my_data[i].sync_time);
                    if(pointer <= time) {
                      pointerIndex = i;
                      showMarker(pointerIndex);
                      break;
                    }
                  }
                }
              }
            });
            // generate Markers
            generateMarkers();
        });
      }

      // shows 1 marker, at the wanted position
      function showMarker(index) {
        var position = {lat: Number(my_data[index].lat), lng: Number(my_data[index].lng)};
        marker.setPosition(position);
      }

      //http://stackoverflow.com/questions/1669190/javascript-min-max-array-values
      Array.prototype.max = function() {
        return Math.max.apply(null, this);
      };
      Array.prototype.min = function() {
        return Math.min.apply(null, this);
      };
    </script>
  </body>
</html>

date.json

[
  {"lat": 28.418871185756046, "lng": 77.03988238780516, "name":"00", "location": "", "sync_time":"2016-10-12 15:58:05", "vehicleNo": "Abhishek"},
  {"lat": 28.414201027385680, "lng": 77.04124510288238, "name":"01", "location": "", "sync_time":"2016-10-12 15:59:05", "vehicleNo": "Abhishek"},
  {"lat": 28.410076539302824, "lng": 77.04258605449217, "name":"02", "location": "", "sync_time":"2016-10-12 16:00:05", "vehicleNo": "Abhishek"},
  {"lat": 28.407142409664587, "lng": 77.04351425170898, "name":"03", "location": "", "sync_time":"2016-10-12 16:02:05", "vehicleNo": "Abhishek"},
  {"lat": 28.404980594548426, "lng": 77.04391643016356, "name":"04", "location": "", "sync_time":"2016-10-12 16:04:05", "vehicleNo": "Abhishek"}
]
Emmanuel Delay
  • 3,619
  • 1
  • 11
  • 17