javascript - 路线建立后如何在google map api中更改路线颜色

标签 javascript google-maps google-maps-api-3 map-directions

您会发现许多已经给出的答案,展示了如何在其上构建具有不同颜色的路线 how to change the color of route in google maps v3

我想知道如何在构建和渲染颜色后更改颜色。

我在 map 上显示了许多不同的路线,但我想显示红色或更深的颜色,如果这个方向点处于事件状态,并将其他路线颜色更改为灰色,直到其中一个处于事件状态。

代码:

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

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer({
    polylineOptions: {
      strokeColor: "red"
    }
  });

  var mapOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: {lat: 41.850033, lng: -87.6500523}
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

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

展示它如何不使用两条路线的演示:http://jsfiddle.net/8xq4gd8y/15/

最佳答案

directionsRenderer 类有一个setOptions 方法。查看documentation .

directionsDisplay.setOptions({
  polylineOptions: {
    strokeColor: 'red'
  }
});

为此,您需要将其从 map 中移除并重新添加以查看颜色变化。

例如在一个事件监听器中,你会做:

google.maps.event.addListener(map, 'click', function() {

  directionsDisplay.setMap(null);

  directionsDisplay.setOptions({
    polylineOptions: {
      strokeColor: 'blue'
    }
  });

  directionsDisplay.setMap(map);
});

JSFiddle demo

关于javascript - 路线建立后如何在google map api中更改路线颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35597394/

相关文章:

Android 缺少标记图像

html - 谷歌地图圈在谷歌浏览器边界半径溢出中不起作用

javascript - 谷歌地图标记动画的IE问题

javascript - 它将打印什么 console.log(1+ + "2")

javascript - 监听特定端口时接收广播包

javascript - 如何优雅地处理 iframe 断路器?

javascript - 隐藏部分 map

javascript - 想在 React Native CookieManager.clearAll() 中清除 webView 的缓存;不适用于 iOS

html - CSS 透明覆盖 Google map

javascript - 关闭 Google Maps MouseWheel Zoom Ctrl