address和coordinates互换
by Frank Liu
JavaScript
async function getAddressByCoordinates(latitude, longitude) {
const url = `https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const data = await response.json();
return data.address;
} catch (error) {
console.error("Failed to fetch address:", error);
}
}
// Example usage:
getAddressByCoordinates(51.5074, -0.1278).then(address => {
console.log("Address:", address);
});
async function getDisplayAddress(latitude, longitude) {
const url = `https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const data = await response.json();
return data.display_name; // Get the display address
} catch (error) {
console.error("Failed to fetch display address:", error);
}
}
// Example usage:
getDisplayAddress(51.523512032989295, -0.38089766617807974).then(displayAddress => {
console.log("Display Address:", displayAddress);
});