簡體   English   中英

使用Google Maps API的未定義Javascript變量

[英]Undefined Javascript variable using Google Maps API

我正在使用Google Maps Javacript API繪制折線。 我打算創建一個單擊按鈕時刪除折線的函數。 該按鈕的HTML代碼如下:

<button type="button" class="btn btn-danger" id="clear_button" onclick="removeLine()">Borrar ruta</button>

接下來是繪制折線並將其刪除的Javascript代碼:

    var map;
    var flightPath;
    function initMap() {

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 17,
            center: {lat: 37.176709, lng: -3.599057},
            mapTypeId: 'terrain'
        });

        google.maps.event.addDomListener(document.getElementById('route_button'), 'click', function() {
            var date_data = document.getElementById('datepicker').value;
            console.log(date_data);
            $.ajax({
                url:"data_fetcher.php",
                type:"POST",
                data: {date_value:date_data},        
                dataType: 'json',
                success: function(respond){
                    var flightPlanCoordinates = respond; 
                    var flightPath = new google.maps.Polyline({
                        path: flightPlanCoordinates,
                        geodesic: true,
                        strokeColor: '#FF0000',
                        strokeOpacity: 1.0,
                        strokeWeight: 2
                    });
                     flightPath.setMap(map);        
                     console.log("AJAX level request was successful");
                },
                error: function(){
                    console.log("AJAX level request was a failure");
                }
            });
        });
    }

    // Eliminar polilinea
    function removeLine() {
    flightPath.setMap(null);
  }

一切正常,但是當我單擊按鈕以刪除折線時,控制台將引發以下錯誤:

未捕獲的TypeError:無法讀取HTMLButtonElement.onclick(device.php:196)的removeLine(device.php:101)上未定義的屬性'setMap'

即使我在全局范圍內聲明了flightPath var。 每一個幫助將不勝感激。

在成功函數中,您要聲明一個具有相同名稱的局部變量,JS將在分配變量時使用它找到的最接近的變量。 要解決此問題,只需刪除var

success: function (respond) {
    var flightPlanCoordinates = respond;
    flightPath = new google.maps.Polyline({
        path: flightPlanCoordinates,
        geodesic: true,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
    flightPath.setMap(map);
    console.log("AJAX level request was successful");
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM