在谷歌地图中显示滑块更改时的标记

时间:2016-10-21 08:40:52

标签: javascript jquery xml google-maps google-maps-markers

地图代码从这里开始。 我现在在当地工作, 折线和动画我可以稍后调整。 Slider有两个变量,所以我想要滑块范围的标记。  我正在尝试使用onchange功能,但我不知道如何再次获取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);
  }
 });

我想要的只是当我移动滑块时它会获得标记的值并显示我的xml文件包含同步时间的标记。这是我的xml文件。  它实际上并不像这样,它的格式化,但这些是属性。 滑块功能获取xml文件同步时间,因此使用此同步时间和滑块时间,它会在谷歌地图上显示正确的标记或路径。

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

请帮帮我。

1 个答案:

答案 0 :(得分:0)

试试这个

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

所以我将时间转换为unix秒,这样可以得到很好的整数。 我只是将滑块的最小值和最大值设置为最小和最大unix秒。

交换你的谷歌API密钥

Array (1, 2, 3)

date.json

<!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>