geoJson parse issue

17 Views Asked by At

I keep getting an error on my code that says: "AJAX Error: parsererror SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

Or it will sometimes say: "GeoJSON file not found"

Ive done all thats been suggested but just seem to be going round in circles - Seems to be with my file name i think but its in the same directory as my php file?

    <?php
header("Content-Type: application/json");

// Enable error reporting for debugging purposes
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('user_agent', 'Your-Application-Name');

// Check if 'country' parameter is provided
if (!isset($_REQUEST['country'])) {
    // Return an error response if the 'country' parameter is missing
    echo json_encode(array(
        'status' => array(
            'code' => 400,
            'name' => 'Bad Request',
            'description' => 'Country parameter is missing'
        ),
        'data' => null
    ));
    exit();
}

// Get the user-specified country from the request
$userCountry = $_REQUEST['country'];

// Use a geocoding service to obtain coordinates
$geocodingUrl = 'https://nominatim.openstreetmap.org/search?format=json&q=' . urlencode($userCountry);
$geocodingData = file_get_contents($geocodingUrl);
$geocodingResult = json_decode($geocodingData, true);

if (empty($geocodingResult)) {
    // Return an error response if the geocoding service does not provide coordinates
    echo json_encode(array(
        'status' => array(
            'code' => 404,
            'name' => 'Not Found',
            'description' => 'Coordinates not found for the specified country'
        ),
        'data' => null
    ));
    exit();
}

// Debugging information
echo "Current working directory: " . getcwd() . "<br>";

// File existence check for GeoJSON file
$geoJsonFilePath = "libs/countryBorders.geo.json";
echo "File exists: " . (file_exists($geoJsonFilePath) ? 'Yes' : 'No') . "<br>";

if (!file_exists($geoJsonFilePath)) {
    // Return an error response if the GeoJSON file is not found
    echo json_encode(array(
        'status' => array(
            'code' => 404,
            'name' => 'Not Found',
            'description' => 'GeoJSON file not found'
        ),
        'data' => null
    ));
    exit();
}

// Read the GeoJSON file
$geoJsonData = file_get_contents($geoJsonFilePath);
$geoJsonArray = json_decode($geoJsonData, true);

// Extract coordinates from the geocoding result
$latitude = $geocodingResult[0]['lat'];
$longitude = $geocodingResult[0]['lon'];


// Read the GeoJSON file
$geoJsonData = file_get_contents("libs/countryBorders.geo.json");
$geoJsonArray = json_decode($geoJsonData, true);


// Extract country codes and names
$countries = array();
foreach ($geoJsonArray['features'] as $feature) {
    $properties = $feature['properties'];
    $country = array(
        'code' => $properties['ISO_A2'],
        'name' => $properties['ADMIN'],
        'latitude' => $latitude,
        'longitude' => $longitude
    );
    $countries[] = $country;
}

$targetCountryCode = '';  
$targetCountry = null; 

foreach ($countries as $country) {
    if ($country['code'] === $targetCountryCode) {
        $targetCountry = $country;
        break;
    }
}

if ($targetCountry !== null) {
    // Return the border information for the specific country code
    echo json_encode(array(
        'status' => array(
            'code' => 200,
            'name' => 'OK',
            'description' => 'Request successful'
        ),
        'data' => $targetCountry,
        'latitude' => $latitude,
        'longitude' => $longitude
    ));
} else {
    // Return an error response if the country code is not found
    echo json_encode(array(
        'status' => array(
            'code' => 404,
            'name' => 'Not Found',
            'description' => 'Country code not found'
        ),
        'data' => null
    ));
}

my geoJson file is called countryBorders.geo.json

document.addEventListener('DOMContentLoaded', function () {

    /* SECTION FOR LEAFLET MAP BASIC SETTINGS */

    // Creates a Leaflet Map and sets the initial view/starting point with coordinates
    const map = L.map('map').setView([0, 0], 2);

    // Adds the OpenStreetMap layer to the map and sets the max zoom level 
    const OpenStreetMap_Mapnik = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(map);

    // Feature Group 
    let featureGroup = L.featureGroup().addTo(map);

    // Load your GeoJSON data and add it to the FeatureGroup
    $.getJSON('libs/countryBorders.geo.json', function (data) {

        let geoJsonLayer = L.geoJSON(data, {
            style: {
                color: 'black',
                weight: 0.5,
                fillOpacity: 0
            }
        });

        // Add the GeoJSON layer to the FeatureGroup
        geoJsonLayer.addTo(featureGroup);

        // Fit the map view to the bounds of the FeatureGroup
        map.fitBounds(featureGroup.getBounds());

    });

    console.log('FeatureGroup:', featureGroup);

    // Create a GeoJSON layer
    let countryBordersLayer = L.geoJSON().addTo(map);


    // Load countryBorders.geo.json data and add it to the GeoJSON layer
    $.getJSON('libs/countryBorders.geo.json', function (data) {
        // Assuming 'countryBordersLayer' is a GeoJSON layer, add the data to it
        countryBordersLayer.addData(data);
    });

    // Will zoom into the user's location once shared - geolocation
    map.locate({ setView: true, maxZoom: 16 });

    // Places a marker in the user's location to show accuracy
    function onLocationFound(e) {
        const radius = e.accuracy;

        L.marker(e.latlng).addTo(map)
            .bindPopup("You are within " + radius + " meters from this point").openPopup();

        L.circle(e.latlng, radius).addTo(map);
    }

    // Defines functions of whether the location of the user was found or error if not
    map.on('locationfound', onLocationFound);

    // Error message if the geolocation failed    
    function onLocationError(e) {
        alert(e.message);
    }

    map.on('locationerror', onLocationError);

    /* SECTION FOR USER INPUT AND LEAFLET MAP MOVING TO THAT COUNTRY */

    document.getElementById('btnRun').addEventListener('click', function () {

        // Retrieves user input 
        let country = document.getElementById('country').value;

        console.log('country:', country);

        // Use OpenStreetMap Nominatim for geocoding
        let geocodeUrl = 'https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(country);

        function successCallback(position) {
            // Handle success, e.g., update the map or perform other actions
        }
        
        function errorCallback(error) {
            // Handle error, e.g., display an error message
            console.error('Error getting geolocation:', error.message);
        }

        // Make an AJAX request to get the geocoded data
        fetch(geocodeUrl)
            .then(response => response.json())
            .then(data => {
                // Get the first result (assuming it's the most relevant)
                let result = data[0];

                // Check if a valid result is obtained
                if (result) {
                    var lat = parseFloat(result.lat);
                    var lon = parseFloat(result.lon);

                    // Set the map view to the user's country
                    map.setView([lat, lon], 6);
                    navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
                } else {
                    console.error('Unable to geocode user input.');
                }
            })
            .catch(error => {
                console.error('Error fetching geocoding data:', error);
            });

        // API Call 
        // Make an AJAX request to the PHP script
        $.ajax({
            url: "libs/countryBorders.php",
            type: 'GET',
            dataType: 'json',
            data: {
                country: $('#country').val(),
            },

            // Callback function to handle a successful result
            success: function (result) {

                console.log(result);

                if (result && result.status && result.status.name === "ok") {

                    let countryInfo = result.data.geonames[0];
                    let latitude = result.data[0].latitude;
                    let longitude = result.data[0].longitude;

                    $('.info-box').html('<p>Country: ' + countryInfo.name + '</p>' +
                        '<p>Code: ' + countryInfo.code + '</p>' +
                        '<p>Latitude: ' + latitude + '</p>' +
                        '<p>Longitude: ' + longitude + '</p>');

                    // Update the Leaflet map to zoom into the specified country based on the obtained coordinates
                    map.setView([latitude, longitude], 10);

                    // Add a marker at the specified coordinates
                    L.marker([latitude, longitude]).addTo(map)
                        .bindPopup('Country: ' + countryInfo.name)
                        .openPopup();

                    $('#txtCapital').html(result.data.capital);
                    $('#txtPopulation').html(result.data.population);
                    $('#txtCurrency').html(result.data.currency);
                    $('#txtLanguage').html(result.data.language);

                    let coordinates = 'Latitude: ' + countryInfo.north + ', Longitude: ' + countryInfo.east;
                    $('#txtCoordinates').html(coordinates);

                    $('#countryInfoResults').show();
                } else {
                    // Handle other cases, e.g., display an error message
                    console.error("Error:", result ? result.status.description : "Unknown error");
                }

                // Assuming 'data' is the API response
                let apiInformation = JSON.stringify(result, null, 2); // Convert data to a formatted JSON string

                // Display the API information in the element with ID 'countryInfoResults'
                $('#countryInfoResults').text(apiInformation);
            },

            // Callback function to handle the error in the AJAX request
            error: function (jqXHR, textStatus, errorThrown) {
                console.error("AJAX Error:", textStatus, errorThrown);
                console.log('Response Text:', jqXHR.responseText);
            }
        });
    });
});
0

There are 0 best solutions below