javascript-Leaflet将不会显示我的标记,“ TypeError:t为null”

我试图在我的传单地图上显示一个标记.这给我以下错误:TypeError:t为空

使用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;
}
?>

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

$(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);
        }
    });
});
});

解决方法:

哦,又是你.

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

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);
}
上一篇:javascript – 删除传单地图上的图例


下一篇:如何在Javascript中使用传单滑块和markercluster?