【问题标题】:Add polyline to google maps将折线添加到谷歌地图
【发布时间】:2015-12-12 05:12:13
【问题描述】:

我正在尝试向谷歌地图添加折线,以便在更新位置时,点之间有一条线。我有以下代码从地理位置获取 lat lng,通过 ajax 将其发送到数据库,然后将数据添加到折线。折线不显示,我在控制台中收到的错误消息是:

InvalidValueError:不是数组 http://maps.google.com/maps-api-v3/api/js/22/2/intl/en_gb/main.js 第 24 行

<script>
$(document).ready(function() {
          // Initialize the Google Maps API v3
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 17,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = null;

    function autoUpdate() {
      navigator.geolocation.getCurrentPosition(function(position) {  
        var newPoint = new google.maps.LatLng(position.coords.latitude, 
                                              position.coords.longitude);

        if (marker) {
          // Marker already created - Move it
          marker.setPosition(newPoint);
        }
        else {
          // Marker does not exist - Create it
          marker = new google.maps.Marker({
            position: newPoint,
            map: map
          });
        }

        console.log(newPoint);

        longi = newPoint['K'];
        lati = newPoint['G'];

        var ajaxurl = '<?php echo WEB_URL; ?>includes/send-coords.php',

        data =  {
            'latitude': lati,
            'longitude' : longi
        };
        $.post(ajaxurl, data, function (response) {

        });

            // Creates the polyline object
          var polyline = new google.maps.Polyline({
            map: map,
            path: newPoint,
            strokeColor: '#0000FF',
            strokeOpacity: 0.7,
            strokeWeight: 1
          });

        // Center the map on the new position
        map.setCenter(newPoint);
      }); 

      // Call the autoUpdate() function every 5 seconds
      setTimeout(autoUpdate, 5000);
    }

autoUpdate();
});
</script>

【问题讨论】:

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


    【解决方案1】:
    1. 请勿使用 Google Maps Javascript API(newPoint['K']newPoint['G'])的未记录属性,它们可以(并且确实)随着 API 的每个版本而更改。

    2. 错误消息一目了然。 newPoint 不是数组,google.maps.Polylinepath 选项应该是数组。

    【讨论】:

      【解决方案2】:

      path 参数是类型:MVCArray&lt;LatLng&gt;|Array&lt;LatLng|LatLngLiteral&gt;

      PolylineOptions

      因此,您需要将所有newPoint 保存在数组中。然后用作折线的路径。

      查看编辑过的小提琴: http://jsfiddle.net/4mtyu/647/

      【讨论】:

        猜你喜欢
        • 2011-09-09
        • 2013-07-25
        • 2015-07-12
        • 1970-01-01
        • 2019-04-29
        • 1970-01-01
        • 2020-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多