Может кто-нибудь помочь мне понять, что я делаю неправильно?
Вот мой код:
//script.js
// Preloader handling
$(window).on("load", function () {
if ($("#preloader").length) {
$("#preloader").delay(1000).fadeOut("slow", function () {
$(this).remove();
});
}
// ---------------------------------------------------------
// GLOBAL DECLARATIONS
// ---------------------------------------------------------
//store the leaflet map instance
var map;
// store the tile layer interface to change map layers
var layerControl;
var countryData = [];
var borderLayer;
//street map layer
var streets = L.tileLayer("
attribution: "Tiles © Esri — Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012"
}
);
//satellite map layer
var satellite = L.tileLayer("
attribution: "Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community"
}
);
//layers are stored in basemaps variable to facilitate easy switching
var basemaps = {
"Streets": streets,
"Satellite": satellite
};
// buttons
//fa-info icon (Font Awesome) info button in a larger size (fa-xl), which opens a modal with the ID "exampleModal" when clicked
var infoBtn = L.easyButton("fa-info fa-xl", function (btn, map) {
$("#exampleModal").modal("show");
});
// ---------------------------------------------------------
// EVENT HANDLERS
// ---------------------------------------------------------
// initialise map with streets as the default layer once DOM is ready
$(function () {
map = L.map("map", {
layers: [streets]
});
// setView is not required in your application as you will be
// deploying map.fitBounds() on the country border polygon
//adds the layer control to the map allowing the user to toggle between streets and satellite layers
layerControl = L.control.layers(basemaps).addTo(map);
//adds the info button to the map
infoBtn.addTo(map);
//checks if the user has geolocation enabled
//if not, displays an alert
//otherwise, it calls the getPosition function, which gets the user's location
if(!navigator.geolocation) {
alert("Your browser does not support geolocation");
} else {
navigator.geolocation.watchPosition(getPosition);
}
//getPosition fetches latitude, longitude and accuracy from the position object
//and logs them to the console
function getPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//var accuracy = position.coords.accuracy;
//console.log("latitude: ", lat, "longitude: ", lng, "accuracy: ", accuracy);
//TO AMEND: set the map view to the user's location using .fitBounds()
//currently centres the map on the user's location at a zoom level of 6
map.setView([lat, lng], 6);
}
//sends a request to getCountries.php to get a list of countries, expecting a JSON response
$.ajax({
url: "libs/php/getCountries.php",
type: "GET",
dataType: "json",
//if successful, it logs the response to the console
//and constructs options for a dropdown menu (countrySelect)
//based on the returned data
success: function(result) {
//console.log(result);
if (result.status.name == "ok") {
//loop through the data and create an option for each country
result.data.forEach(country => {
countryData.push({
code: country["iso_a2"],
name: country["name"]
})
//console.log(country);
$("")
//adds the country name as text to the dropdown menu
//and country iso code as the value
.val(country["iso_a2"])
.text(country["name"])
//appends the country name and iso code to the select element/ dropdown menu
.appendTo("#countrySelect");
});
}
},
//if an error occurs, logs the error information to the console
error: function(jqXHR, textStatus, errorThrown) {
console.log(`Error: ${textStatus} - ${errorThrown}`);
//console.log(jqXHR.responseText);
}
});
// Handle country selection change to fetch border information
$("#countrySelect").on("change", function() {
var selectedISOCode = $(this).val();
if (!selectedISOCode) {
console.warn("No ISO code selected.");
return;
}
// Perform AJAX request to fetch country borders
$.ajax({
url: 'libs/php/getCountryBorders.php', // Adjust the path as needed
method: 'GET',
data: { iso_code: selectedISOCode }, // Pass the ISO code as a parameter. The ISO code is taken from the dropdown menu and uses the PHP script to fetch the border data
dataType: 'json',
success: function(response) {
if (response.status.name !== "ok") {
console.error(response.status.description);
return;
}
// Access the border coordinates from the response data
const borderCoordinates = response.data;
console.log(borderCoordinates);
// Optional: clear any existing map layers
if (typeof borderLayer !== 'undefined') {
borderLayer.remove();
}
//Otherwise, create a new Leaflet GeoJSON layer for the borders
borderLayer = L.geoJSON(borderCoordinates).addTo(map);
//Add styling to the border layer
borderLayer.setStyle({
fillColor: "#ff1234",
weight: 2,
fillOpacity: 1
})
//Zoom the map to fit the borders
map.fitBounds(borderLayer.getBounds());
},
error: function(xhr, status, error) {
console.error("Error fetching country borders:", error);
}
});
});
});
});
//example entry from countryBorders.geo.json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Bahamas",
"iso_a2": "BS",
"iso_a3": "BHS",
"iso_n3": "044"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-77.53466, 23.75975],
[-77.78, 23.71],
[-78.03405, 24.28615],
[-78.40848, 24.57564],
[-78.19087, 25.2103],
[-77.89, 25.17],
[-77.54, 24.34],
[-77.53466, 23.75975]
]
],
[
[
[-77.82, 26.58],
[-78.91, 26.42],
[-78.98, 26.79],
[-78.51, 26.87],
[-77.85, 26.84],
[-77.82, 26.58]
]
],
[
[
[-77, 26.59],
[-77.17255, 25.87918],
[-77.35641, 26.00735],
[-77.34, 26.53],
[-77.78802, 26.92516],
[-77.79, 27.04],
[-77, 26.59]
]
]
]
}
Я попробовал изменить значение borderCoordinates в script.js и записать его в консоль, но не смог определить, какая структура будет лучшей. Например, когда я ставлю
const borderCoordinates = response.data[0];
Я получаю:
Map.js:291 Uncaught Error: Bounds are not valid.
at e.fitBounds (Map.js:291:10)
at Object.success (script.js:170:13)
at c (jquery-3.6.0.min.js:2:28327)
at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2:29072)
at l (jquery-3.6.0.min.js:2:79901)
at XMLHttpRequest. (jquery-3.6.0.min.js:2:82355)
Подробнее здесь: https://stackoverflow.com/questions/791 ... -country-c
Мобильная версия