谷歌地图,如何将折线lat / lng保存为热图可视化的数据阵列?

时间:2017-03-10 13:03:15

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

我正在尝试将用户制作的折线路径保存为按钮单击时热图可视化的数据阵列。

目前我正在尝试使用预设数据生成热图,并且恰好会出现错误:未捕获的TypeError:无法在toggleHeatmap中读取未定义的属性“setMap”

是否有人能够提供以下解决方案: 1 - 使热图显示至少与预设数据一起显示。 2 - 将用户制作的折线中的数据提取到数据数组中。

非常感谢提前!

   <script>

    var poly;
    var map;
    var markers = [];
    var heatmap;


    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 14,
            center: {lat: 60.1675, lng: 24.9311},
            zoomControl: false,
            scaleControl: false,
            scrollwheel: false,
            draggable: false,
            disableDoubleClickZoom: true
        });

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

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

        heatmap = new google.maps.visualization.HeatmapLayer({
            data: getPoints(),
            map: map
        });
    }


    function toggleHeatmap() {

        heatmap.setMap(heatmap.getMap() ? null : map);
    }

    function getPoints() {
        return [
            new google.maps.LatLng(60.1675, 24.9211),
            new google.maps.LatLng(60.1675, 24.9212),
            new google.maps.LatLng(60.1675, 24.9213)
        ]
    }


    // Handles click events on a map, and adds a new point to the Polyline.
    function addLatLng(event) {
        var path = poly.getPath();
        path.push(event.latLng);

        var marker = new google.maps.Marker({
            position: event.latLng,
            title: '#' + path.getLength(),
            map: map
        });
        markers.push(marker);
    }

    // Sets the map on all markers in the array.
    function setMapOnAll(map) {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
        }
    }

    // Removes the markers from the map, but keeps them in the array.
    function clearMarkers() {
        setMapOnAll(null);
    }

    // Shows any markers currently in the array.
    function showMarkers() {
        setMapOnAll(map);
    }

    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
        clearMarkers();
        markers = [];
    }

    //Function to remove lines
    function removeLine() {
        var path = poly.getPath();
        path.clear();

    }

    function clearPath() {
        removeLine();
        clearMarkers();
    }


</script>

1 个答案:

答案 0 :(得分:0)

想出来,问题是由API脚本引起的。需要添加&#34;&amp; libraries = visualization&#34;在API密钥之后如下:

<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=visualization">
</script>