我可以在google maps API上连接两个标记吗?

时间:2016-04-05 09:10:49

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

我希望功能是,当用户点击位置A的标记时,会出现一条通往位置B的线。我试图创建一张地图,显示人们出生的地方以及他们在哪里现在住

就像瑞安航空的网站一样,你将鼠标悬停在伦敦上,然后你会看到他们飞往的所有目的地。

谢谢,

1 个答案:

答案 0 :(得分:0)

我创造了一个简单的例子 我希望我理解你的要求
这是代码:

// Marker locations
var locations = [
  ['A', -33.890542, 151.274856, 4],
  ['B', -33.923036, 151.139052, 5]
];
var map;
var markers = [];

function init(){
  // Create new Map
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 10,
    center: new google.maps.LatLng(-33.92, 151.25),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  // Get number of Locations
  var num_markers = locations.length;
  // Create Markers
  for (var i = 0; i < num_markers; i++) {  
    markers[i] = new google.maps.Marker({
      position: {lat:locations[i][1], lng:locations[i][2]},
      map: map,
      html: locations[i][0],
      id: i,
    });
    // Add onClick Marker Listener
    google.maps.event.addListener(markers[i], 'click', function(){
      // Create Line
      var flightPath = new google.maps.Polyline({
        path: [{lat:locations[0][1], lng:locations[0][2]}, {lat:locations[1][1], lng:locations[1][2]}],
        geodesic: true,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
      });
      // Add line to map
      flightPath.setMap(map);
    });
    }
}

init();
#map_canvas { 
  border:1px solid black;
  height: 400px;
  width: 100%;
  border-radius: 4px;
}
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map_canvas"></div>


或者你可以试试JSFiddle

再见。