javascript - 为位于路线上的谷歌地图标记设置信息窗口(起点和终点)

标签 javascript google-maps google-maps-api-3 google-maps-markers

嗨,我正在我的代码中在两个标记之间绘制一条路线。我需要完成的是将单击事件添加到这两个标记,并为每个标记设置一个信息窗口。我搜索了很多网站都找不到解决方案。尽管它绘制了标记之间的路线,但无法为每个标记设置信息窗口。这是我的代码...

                   function mapLocation() {
                        var directionsDisplay;
                        var directionsService = new google.maps.DirectionsService();
                        var map;

                        function initialize() {
                            directionsDisplay = new google.maps.DirectionsRenderer();
                            var chicago = new google.maps.LatLng(37.334818, -121.884886);
                            var mapOptions = {
                                zoom: 7,
                                center: chicago
                            };
                            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                            directionsDisplay.setMap(map);
                            google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute);
                        }

                        function calcRoute() {
                            var start = new google.maps.LatLng(37.334818, -121.884886);
                            //var end = new google.maps.LatLng(38.334818, -181.884886);
                            var end = new google.maps.LatLng(37.441883, -122.143019);
                            var request = {
                                origin: start,
                                destination: end,
                                travelMode: google.maps.TravelMode.DRIVING
                            };
                            directionsService.route(request, function (response, status) {
                                if (status == google.maps.DirectionsStatus.OK) {
                                    directionsDisplay.setDirections(response);
                                    directionsDisplay.setMap(map);
                                } else {
                                    alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
                                }
                            });
                        }

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

最佳答案

您不能仅使用 InfoWindow 添加点击监听器。您需要使用 DirectionsRenderer 的 {suppressMarkers} 选项,然后解析响应中所需的信息以添加您自己的标记。

根据我的示例进行修改:http://www.geocodezip.com/v3_directions_custom_iconsC.html

代码片段:

function mapLocation() {
  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  var infowindow;

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer({
      suppressMarkers: true
    });
    var chicago = new google.maps.LatLng(37.334818, -121.884886);
    var mapOptions = {
      zoom: 7,
      center: chicago
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    infowindow = new google.maps.InfoWindow();
    directionsDisplay.setMap(map);
    google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute);
  }

  function calcRoute() {
    var start = new google.maps.LatLng(37.334818, -121.884886);
    var end = new google.maps.LatLng(37.441883, -122.143019);
    var waypoint = {
      location: new google.maps.LatLng(37.432334, -121.899574)
    };
    var waypoint2 = {
      location: new google.maps.LatLng(37.54827, -121.988572)
    };
    var request = {
      origin: start,
      destination: end,
      waypoints: [waypoint, waypoint2],
      travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        directionsDisplay.setMap(map);

        var startLocation = new Object();
        var endLocation = new Object();
        var waypointLocations = [];

        // Display start and end markers for the route.
        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;
            // createMarker(legs[i].start_location, "start", legs[i].start_address, "green");
          }
          if (i != 0 && i != legs.length - 1) { 
            var waypoint = {};
            waypoint.latlng = legs[i].start_location;
            waypoint.address = legs[i].start_address;
            waypointLocations.push(waypoint);
          }
          if (i == legs.length - 1) {
            endLocation.latlng = legs[i].end_location;
            endLocation.address = legs[i].end_address;
          }
          var steps = legs[i].steps;
        }
        createMarker(endLocation.latlng, "end", "special text for end marker", "http://www.google.com/mapfiles/markerB.png")
        createMarker(startLocation.latlng, "start", "special text for start marker", "http://maps.gstatic.com/mapfiles/markers2/marker_greenA.png");
        for (var i = 0; i < waypointLocations.length; i++) {
          createMarker(waypointLocations[i].latlng, "waypoint " + i, "special text for waypoint marker " + i, "http://www.google.com/mapfiles/marker_yellow.png");
        }
      } else {
        alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
      }
    });
  }

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

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


// http://www.google.com/mapfiles/markerB.png


mapLocation();
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="routebtn" type="button" value="route" />
<div id="map-canvas"></div>

关于javascript - 为位于路线上的谷歌地图标记设置信息窗口(起点和终点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29361044/

相关文章:

javascript - 在Javascript中按顺序向上和向下计数到指定的数字

javascript - React,组件多次调用我的后端

javascript - 素面 : get geocoder address from google Map to ManagedBean

google-maps - 初创公司的地理编码服务?

java - 如何从Android中的另一个 Activity 调用MapActivity的方法?

google-maps - 如何使 Google map 居中而不位于屏幕中心?

javascript - 从 GeocoderResult 获取 formatted_address 组件

javascript - 通过 javascript 和 ajax 填充 HTML 页面的最佳策略

javascript - 将绑定(bind)应用与数组参数一起使用时参数丢失

java - 识别触发 onTap 调用的 GeoPoint