javascript - 将折线添加到谷歌地图

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

我正在尝试向谷歌地图添加一条折线,以便在更新位置时,点之间有一条线。我有以下代码,从地理位置获取 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>

最佳答案

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

  2. 错误消息是不言自明的。 newPoint 不是数组,google.maps.Polylinepath 选项应该是数组。

关于javascript - 将折线添加到谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32594652/

相关文章:

javascript - 如何使用javascript更新html框架之外的html?

javascript - 当滚动达到 80% 时加载 ajax

javascript - 使用 select by id 在特定传单弹出窗口中创建图形

android - 有没有办法通过 Google API 获取用户的 "home"和 "work"位置?

javascript - 如何在 PHP 中邮寄动态生成的下拉字段值?

javascript - 样式化 iframe 内容

用于 UI 组件的 Javascript 包或库

javascript - 悬停时的 Jquery 无法正常工作

android - 聚类在 Android 版谷歌地图中不起作用。我究竟做错了什么?

java - 使用 Google Maps Android - 读取 CSV 文件问题