Leaflet 不会显示我的标记,“TypeError: t is null”

TJ *_*J W 3 javascript php jquery coordinates leaflet

我试图在我的传单地图上显示一个标记。这给了我以下错误:TypeError: t is null

使用 Google Maps 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;
}
?>
Run Code Online (Sandbox Code Playgroud)

jQuery 运行 PHP 脚本并应在 Leaflet 地图上显示坐标:

$(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);
        }
    });
});
});
Run Code Online (Sandbox Code Playgroud)

Vic*_*Vic 5

哦,又是你。

您收到一个字符串作为响应。

L.marker 期望[lat, lng]但你给它["lat, lng"]一个字符串而不是两个浮点数。

要在 JavaScript 中解决此问题:

success: function(response){
    var coordinates = response.split(", "); //create an array containing lat and lng as strings
    coordinates[0] = parseFloat(coordinates[0]); //convert lat string to number
    coordinates[1] = parseFloat(coordinates[1]); //convert lng string to number
    var marker = L.marker(coordinates).addTo(map);
}
Run Code Online (Sandbox Code Playgroud)

  • 天才!今天我从你的分割阵列中学到了一些新东西。真诚地感谢您对我的帮助。 (2认同)