谷歌地图折线阵列

时间:2013-01-22 15:18:50

标签: google-maps

我是谷歌地图应用程序的新手。我读过一篇关于Polyline Arrays的文章(https://developers.google.com/maps/documentation/javascript/overlays#PolylineArrays)。在该示例中,它使用Event Click创建了动态数组。我的问题是,我是否可以在数组变量中创建折线而不是在点击事件上?

以下是Google文档中的代码:

var poly;
var map;

function initialize() {
  var chicago = new google.maps.LatLng(41.879535, -87.624333);
  var mapOptions = {
    zoom: 7,
    center: chicago,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

  var polyOptions = {
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3
  }
  poly = new google.maps.Polyline(polyOptions);
  poly.setMap(map);

  // Add a listener for the click event
  google.maps.event.addListener(map, 'click', addLatLng);
}

/**
 * Handles click events on a map, and adds a new point to the Polyline.
 * @param {MouseEvent} mouseEvent
 */
function addLatLng(event) {

  var path = poly.getPath();

  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear
  path.push(event.latLng);

  // Add a new marker at the new plotted point on the polyline.
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
}

我已经制作了一些自己的代码:

<script>
        var line;
        var map;
        function initialize() {
            var mapDiv = document.getElementById('map-canvas');
            map = new google.maps.Map(mapDiv, {
                center: new google.maps.LatLng(0, -180),
                zoom: 2,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            var path = [new google.maps.LatLng(37.772323, -122.214897),
                new google.maps.LatLng(21.291982, -157.821856)];

            line = new google.maps.Polyline({
                path: path,
                strokeColor: '#ff0000',
                strokeOpacity: 1.0,
                strokeWeight: 2
            });

            line.setMap(map)
        }

        function addNewPoint(position) {
            var path = line.getPath();
            path.push(position);
        }

        ''''' I create a single variable for a new path.
        var NewPath = [new google.maps.LatLng(-27.46758, 153.027892)];
        addNewPoint(NewPath);

        google.maps.event.addDomListener(window, 'load', initialize);
    </script>

当我跑的时候。这是行不通的。谢谢你的回复。

1 个答案:

答案 0 :(得分:0)

我认为你需要改变这个:

var NewPath = [new google.maps.LatLng(-27.46758, 153.027892)];
addNewPoint(NewPath);

到此:

var NewPath = new google.maps.LatLng(-27.46758, 153.027892);
addNewPoint(NewPath);

因此,您只能通过LatLng点,而不是包含一个的数组。所以它更贴近你给出的例子,

path.push(event.latLng);