2017-03-18 19 views
0

我試圖在我的Leaflet地圖上顯示一個標記。這給了我下面的錯誤:類型錯誤:t爲空傳單不會顯示我的標記,「TypeError:t爲null」

它使用谷歌地圖API來獲取座標

PHP代碼:

<?php 
if (isset($_POST["checkAddress"])) { //Checks if action value exists 
    $checkAddress = $_POST["checkAddress"]; 
    $plus = str_replace(" ", "+", $checkAddress); 
    $json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=KEY'); 
    $obj = json_decode($json); 
    $mapLat = $obj->results[0]->geometry->location->lat; 
    $mapLng = $obj->results[0]->geometry->location->lng; 
    $coords = ('' . $mapLat . ', ' . $mapLng . ''); 
    echo $coords; 
} 
?> 

jQuery的它運行PHP腳本,並應顯示座標宣傳單圖:

$(document).ready(function() { 
$("#button").click(function(){ 
    $.ajax({ 
     url: "geo.php", 
     method: "POST", 
     data: { 
     checkAddress: $("#largetxt").val() 
     }, 
     success: function(response){ 
     console.log(response); 
     var marker = L.marker([response]).addTo(map); 
     } 
    }); 
}); 
}); 

回答

0

哦,這是你。

您正在收到一個字符串作爲迴應。

L.marker預計[lat, lng]但你給它["lat, lng"]一個字符串,而不是兩個浮點數。

在JavaScript中解決這個問題:

+0

天才!我今天用分割數組學習了一些新東西。真心謝謝你的幫助。 –

+0

我建議你用PHP和'json_encode'創建一個數組。然後,在JavaScript中使用'JSON.parse'。 @TJW – Vic