1

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

这是来自谷歌文档的代码:

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>

当我运行它时。这没用。感谢您的任何回复。

4

1 回答 1

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);
于 2013-01-22T15:53:14.203 回答