通过点击kml标记的infoWindow获取latLng,用于DirectionsService()

时间:2018-03-09 20:47:58

标签: javascript google-maps kml marker infowindow

我有一个简单的JS脚本,通过读取带有一个地方标记列表的kml文件在谷歌地图上显示标记,并显示用户的当前位置。 默认情况下,点击标记会在infoWindow中显示每个地标的名称和说明。

我的问题是如何添加一个选项来运行directionsService.route(directionsRequest, ...)任何选定的标记是目的地,当前位置是起点(双击标记或在{{1}中添加一个链接似乎是最直观的方式,但也许有人有更好的主意)......

这是当前基本的JS脚本(现在运行正常,使用https://maps.googleapis.com/maps/api/js?key=IDXXX调用API,但它消除了仅查看标记信息的可能性,因为单击标记会立即触发路径渲染):

infoWindow

然后通过点击任何kml标记来获取latLng,以显示要遵循的路线,但是我想要另一个选项而不是“点击”,以便能够在不触发路线的情况下查看infowindows数据(如果我放下面var map; function initialize() { var center_map = new google.maps.LatLng(45,-4); var mapOptions = { zoom: zoomvalue, // defined on the page center: center_map, mapTypeId: google.maps.MapTypeId.SATELLITE, scaleControl: true }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); var ctaLayer = new google.maps.KmlLayer({ url: urlkmlfile, // defini sur page qui appelle ce script preserveViewport: false }); ctaLayer.setMap(map); if(navigator.geolocation) { navigator.geolocation.watchPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); if(typeof pos_infowindow == "undefined") { pos_infowindow = new google.maps.InfoWindow({ disableAutoPan: true, map: map, position: pos, content: 'Votre position' }); } else { pos_infowindow.setPosition(pos); } // add code here }, function() { // alert('no geolocation'); }, { timeout: 15000, enableHighAccuracy: true } ); } }; google.maps.event.addDomListener(window, 'load', initialize); 事件中的'dblClick',它仍然只放大):

addListener

有一种简单的方法吗?我想保留“点击”事件以读取每个标记的数据,并发送“dblClick”事件或if (pos) google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) { var name_marker = kmlEvent.featureData.name; var text_marker = kmlEvent.featureData.description; var pos_marker = kmlEvent.latLng; var offset_marker = kmlEvent.pixelOffset; var directionsService = new google.maps.DirectionsService(); var directionsRequest = { origin: pos, destination: pos_marker, travelMode: google.maps.DirectionsTravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC }; // alert('start ' + pos + ' destination ' + pos_marker); directionsService.route( directionsRequest, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { new google.maps.DirectionsRenderer({ map: map, directions: response }); } else{ // alert ('problem'); } }); }); 中添加的链接,以触发infoWindow我想保留它简单。

1 个答案:

答案 0 :(得分:1)

KmlLayer不支持双击事件(它支持的唯一鼠标事件是点击)。

一种选择是在infowindow中为呈现的HTML添加“获取路线”链接,然后使用该点击事件的event.latLng作为目的地:

ctaLayer.addListener("click", function(event) {
  infowindow.setContent(event.featureData.infoWindowHtml+"<br><a href='javascript:getDirections("+event.latLng.toUrlValue(6)+");'>get directions</a>");
  infowindow.setOptions({pixelOffset: event.pixelOffset});
  infowindow.setPosition(event.latLng);
  infowindow.open(map);
});

function getDirections(lat, lng) {
  start = pos_infowindow.getPosition(); // current position as defined in the geolocation function
  var latLng = new google.maps.LatLng(lat, lng);
  destination = latLng; // position of the marker clicked, as defined by the kml file
  var directionsService = new google.maps.DirectionsService();
  var directionsRequest = {
    origin: start,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC
  };
  directionsService.route(directionsRequest, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else
      alert('Directions Request failed: ' + status);
  });
}

proof of concept fiddle

screenshot of resulting map

代码段

var map;
var pos_infowindow;
var infowindow;
var directionsDisplay;

function initialize() {
  var center_map = new google.maps.LatLng(45, -4);
  var infowindow = new google.maps.InfoWindow();
  var mapOptions = {
    zoom: 5, // defined on the page
    center: {
      lat: 0,
      lng: 0
    },
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    scaleControl: true
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay = new google.maps.DirectionsRenderer({
    map: map
  });
  var ctaLayer = new google.maps.KmlLayer({
    url: "http://www.geocodezip.com/state_capitals.xml", // defini sur page qui appelle ce script
    preserveViewport: false,
    suppressInfoWindows: true
  });
  ctaLayer.setMap(map);
  ctaLayer.addListener("click", function(event) {
    infowindow.setContent(event.featureData.infoWindowHtml + "<br><a href='javascript:getDirections(" + event.latLng.toUrlValue(6) + ");'>get directions</a>");
    infowindow.setOptions({
      pixelOffset: event.pixelOffset
    });
    infowindow.setPosition(event.latLng);
    infowindow.open(map);
  });

  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(function(position) {
        var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        if (typeof pos_infowindow == "undefined") {
          pos_infowindow = new google.maps.InfoWindow({
            disableAutoPan: true,
            map: map,
            position: pos,
            content: 'Votre position'
          });
        } else {
          pos_infowindow.setPosition(pos);
        }
        // add code here
      },
      function() {
        alert('no geolocation');
        pos_infowindow = new google.maps.InfoWindow({
          disableAutoPan: true,
          map: map,
          position: {
            lat: 39.011902,
            lng: -98.4842465
          }, // default to Kansas
          content: 'Votre position'
        });
      }, {
        timeout: 15000,
        enableHighAccuracy: true
      }
    );
  }
}

google.maps.event.addDomListener(window, 'load', initialize);

function getDirections(lat, lng) {
  start = pos_infowindow.getPosition(); // current position as defined in the geolocation function
  var latLng = new google.maps.LatLng(lat, lng);
  destination = latLng; // position of the marker clicked, as defined by the kml file
  var directionsService = new google.maps.DirectionsService();
  var directionsRequest = {
    origin: start,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC
  };
  directionsService.route(directionsRequest, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else
      alert('Directions Request failed: ' + status);
  });
}
html,
body,
#map-canvas {
  height: 90%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id='map-canvas'></div>