Display marker and circle on open Map
by Frank Liu
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Leaflet Map with Nominatim Geocoding</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<style>
#mapid {
height: 500px;
}
</style>
</head>
<body>
<div id="mapid"></div>
<input type="text" id="address" placeholder="Enter an address" />
<button id="geocodeBtn">Show on Map</button>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script>
async function getCoordinates(address) {
try {
const url = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}`
const response = await fetch(url)
if (!response.ok) {
throw new Error("Network response was not ok")
}
const data = await response.json()
if (data.length > 0) {
const { lat, lon,display_name } = data[0] // Use the first result
console.log("格式化地址:", display_name);
return { lat, lon }
} else {
throw new Error("No results found for the provided address.")
}
} catch (error) {
console.error("Error fetching coordinates:", error)
alert("Error fetching coordinates: " + error.message)
}
}
function showLocationOnMap(lat, lon, radius) {
try {
const center = [lat, lon]
console.log("get geo code: ", { lat, lon })
// Initialize the Leaflet map
const map = L.map("mapid").setView(center, 13) // Default center
// Add a tile layer (OpenStreetMap)
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "© OpenStreetMap contributors",
}).addTo(map)
// Clear previous markers and circles
map.eachLayer((layer) => {
if (layer instanceof L.Marker || layer instanceof...