I am trying to display a marker on my Leaflet map. This gives me the following error: TypeError: t is null
PHP code which uses Google Maps API to fetch co-ordinates:
<?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 which runs the PHP script and should display the co-ordinates on the Leaflet map:
$(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);
}
});
});
});
Oh, it's you again.
You are receiving a string as a response.
L.marker expects [lat, lng] but you are giving it ["lat, lng"] A string instead of two floats.
To fix this in 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);
}