如何添加具有位置数组的多段线? [英] How to add polylines with an array of position?

查看:79
本文介绍了如何添加具有位置数组的多段线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含城市名称的简单数组。我试图循环访问这个数组,并添加由Google地图上的Polylines链接的标记。



这是我的代码:

 函数addMarkerCity(城市){
$ .each(城市,函数(索引,值){
geocoder.geocode({'address': (状态== google.maps.GeocoderStatus.OK){
var cityPosition = results [0] .geometry.location;
flightRoute。 push(cityPosition);
var currentMarker = map.addMarker({
position:cityPosition
});
});
});
});
}

addMarkerCity函数可以正常工作,并由JQuery事件click()按钮触发。我使用数组flightRoute存储每个标记的每个位置,然后将它传递给将在两个标记之间创建多段线的函数。现在的问题是我只看到地图上的折线,如果我点击两次按钮使它工作。



当我在做:

  console.log(flightRoute); 

数组flightRoute等于[],然后我可以看到之前创建的2的LatLng标记。有人可以告诉我我做错了什么,以获得飞行里面的位置并直接显示标记。

解决方案

为了将折点添加到折线中


  1. 您需要有一个类型为google.maps.MVCArray的数组

    var points = new google.maps.MVCArray();


  2. 您需要通过mvcarray到折线

    var polyline = new google.maps.Polyline({
    path:points
    });



I have a simple array containing name of cities. I'm trying to loop through this array and add markers linked by Polylines on the Google Map.

Here is my code:

 function addMarkerCity(cities) {
   $.each(cities, function(index, value) {
    geocoder.geocode({'address': value}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       var cityPosition = results[0].geometry.location;
       flightRoute.push(cityPosition);
       var currentMarker = map.addMarker({
         position: cityPosition
       });
     });
   });
 });
}

The function addMarkerCity works fine and triggered by a JQuery event click() button. I'm using the array flightRoute to store each position of each marker and then pass it to the function which will create the polyline between the 2 markers.

The problem now is that I only see the polyline on the map if I click twice on the button to make it work.

When I'm doing:

console.log(flightRoute);

The array flightRoute is equal to [] first and then I can see the LatLng of the 2 previously created markers. Can someone tell me what I'm doing wrong, to get the position inside flightRoute and display straight away the markers. I'm very close to get the result that I want.

解决方案

In order to add points to a polyline dinamically

  1. you need to have an array of the type google.maps.MVCArray

    var points = new google.maps.MVCArray();

  2. you need to pass that mvcarray to the polyline

    var polyline = new google.maps.Polyline({ path: points });

这篇关于如何添加具有位置数组的多段线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆