Localities Geocode
Use the LocalitiesService to geocode addresses and reverse geocode locations.
Example
Localities Geocode
// Initialize and add the map
let map: woosmap.map.Map;
let marker: woosmap.map.Marker;
let infoWindow: woosmap.map.InfoWindow;
let localitiesService: woosmap.map.LocalitiesService;
const request: woosmap.map.localities.LocalitiesGeocodeRequest = {};
function initMap() {
map = new window.woosmap.map.Map(
document.getElementById("map") as HTMLElement,
{
center: { lat: 51.50940214, lng: -0.133012 },
zoom: 12,
},
);
infoWindow = new woosmap.map.InfoWindow({});
localitiesService = new woosmap.map.LocalitiesService();
map.addListener("click", (e) => {
handleGeocode(e.latlng);
});
}
const inputElement = document.getElementById(
"autocomplete-input",
) as HTMLInputElement;
const clearSearchBtn = document.getElementsByClassName(
"clear-searchButton",
)[0] as HTMLButtonElement;
if (inputElement) {
inputElement.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
handleGeocode(null);
}
});
inputElement.addEventListener("input", () => {
if (inputElement.value !== "") {
clearSearchBtn.style.display = "block";
} else {
clearSearchBtn.style.display = "none";
}
});
}
clearSearchBtn.addEventListener("click", () => {
inputElement.value = "";
clearSearchBtn.style.display = "none";
if (marker) {
marker.setMap(null);
infoWindow.close();
}
clearResponse();
inputElement.focus();
});
function handleGeocode(latlng: woosmap.map.LatLngLiteral | null) {
if (latlng) {
request.latLng = latlng;
delete request.address;
} else if (inputElement?.value !== "") {
request.address = inputElement.value;
delete request.latLng;
}
if (request.latLng || request.address) {
localitiesService
.geocode(request)
.then((localities) => displayLocality(localities.results[0]))
.catch((error) => console.error("Error geocoding localities:", error));
}
}
function displayLocality(
locality: woosmap.map.localities.LocalitiesGeocodeResult | null,
) {
if (marker) {
marker.setMap(null);
infoWindow.close();
}
if (locality?.geometry) {
marker = new woosmap.map.Marker({
position: locality.geometry.location,
icon: {
url: "https://images.woosmap.com/marker.png",
scaledSize: {
height: 50,
width: 32,
},
},
});
marker.setMap(map);
infoWindow.setContent(`<span>${locality.formatted_address}</span>`);
infoWindow.open(map, marker);
map.setCenter(locality.geometry.location);
renderResponse(locality);
}
}
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function formatNameValue(value: string | string[]): string {
return Array.isArray(value) ? value.join(", ") : value;
}
function renderResponse(
locality: woosmap.map.localities.LocalitiesGeocodeResult,
) {
const panel = document.getElementById("response-panel");
const summaryEl = panel?.querySelector(".summary") as HTMLElement | null;
const componentsEl = panel?.querySelector(
".address-components",
) as HTMLElement | null;
const rawEl = document.getElementById("raw-json");
if (!panel || !summaryEl || !componentsEl || !rawEl) return;
panel.dataset.empty = "false";
const summaryRows: string[] = [];
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Formatted address:</span><span class='bold'>${escapeHtml(locality.formatted_address)}</span></p>`,
);
if (locality.types && locality.types.length) {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Types:</span><span class='bold'>${escapeHtml(locality.types.join(", "))}</span></p>`,
);
}
if (locality.public_id) {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Public ID:</span><span class='bold'>${escapeHtml(locality.public_id)}</span></p>`,
);
}
if (typeof locality.distance === "number") {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Distance (m):</span><span class='bold'>${locality.distance}</span></p>`,
);
}
if (locality.geometry) {
const { geometry } = locality;
if (geometry.location_type) {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Location type:</span><span class='bold'>${escapeHtml(geometry.location_type)}</span></p>`,
);
}
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Latitude:</span><span class='bold'>${geometry.location.lat}</span></p>`,
`<p class='option-detail'><span class='option-detail-label'>Longitude:</span><span class='bold'>${geometry.location.lng}</span></p>`,
);
if (geometry.viewport) {
const { viewport } = geometry;
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Viewport NE:</span><span class='bold'>${viewport.northeast.lat}, ${viewport.northeast.lng}</span></p>`,
`<p class='option-detail'><span class='option-detail-label'>Viewport SW:</span><span class='bold'>${viewport.southwest.lat}, ${viewport.southwest.lng}</span></p>`,
);
}
}
summaryEl.innerHTML = `<div class='section-title'>Summary</div>${summaryRows.join("")}`;
if (locality.address_components && locality.address_components.length) {
const rows = locality.address_components
.map((compo) => {
const label = escapeHtml((compo.types[0] ?? "").replace(/_/g, " "));
const longName = escapeHtml(formatNameValue(compo.long_name));
return `<p class='option-detail'><span class='option-detail-label'>${label}:</span><span class='bold'>${longName}</span></p>`;
})
.join("");
componentsEl.innerHTML = `<div class='section-title'>Address components</div>${rows}`;
} else {
componentsEl.innerHTML = "";
}
rawEl.textContent = JSON.stringify(locality, null, 2);
}
const copyBtn = document.getElementById("copy-raw-json");
if (copyBtn) {
copyBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const rawEl = document.getElementById("raw-json");
const text = rawEl?.textContent ?? "";
if (!text) return;
navigator.clipboard
.writeText(text)
.then(() => {
copyBtn.classList.add("copied");
window.setTimeout(() => copyBtn.classList.remove("copied"), 1500);
})
.catch((err) => console.error("Failed to copy raw JSON:", err));
});
}
function clearResponse() {
const panel = document.getElementById("response-panel");
if (!panel) return;
panel.dataset.empty = "true";
const summaryEl = panel.querySelector(".summary") as HTMLElement | null;
const componentsEl = panel.querySelector(
".address-components",
) as HTMLElement | null;
const rawEl = document.getElementById("raw-json");
if (summaryEl) summaryEl.innerHTML = "";
if (componentsEl) componentsEl.innerHTML = "";
if (rawEl) rawEl.textContent = "";
}
declare global {
interface Window {
initMap: () => void;
}
}
window.initMap = initMap;
// Initialize and add the map
let map;
let marker;
let infoWindow;
let localitiesService;
const request = {};
function initMap() {
map = new window.woosmap.map.Map(document.getElementById("map"), {
center: { lat: 51.50940214, lng: -0.133012 },
zoom: 12,
});
infoWindow = new woosmap.map.InfoWindow({});
localitiesService = new woosmap.map.LocalitiesService();
map.addListener("click", (e) => {
handleGeocode(e.latlng);
});
}
const inputElement = document.getElementById("autocomplete-input");
const clearSearchBtn = document.getElementsByClassName("clear-searchButton")[0];
if (inputElement) {
inputElement.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
handleGeocode(null);
}
});
inputElement.addEventListener("input", () => {
if (inputElement.value !== "") {
clearSearchBtn.style.display = "block";
} else {
clearSearchBtn.style.display = "none";
}
});
}
clearSearchBtn.addEventListener("click", () => {
inputElement.value = "";
clearSearchBtn.style.display = "none";
if (marker) {
marker.setMap(null);
infoWindow.close();
}
clearResponse();
inputElement.focus();
});
function handleGeocode(latlng) {
if (latlng) {
request.latLng = latlng;
delete request.address;
} else if (inputElement?.value !== "") {
request.address = inputElement.value;
delete request.latLng;
}
if (request.latLng || request.address) {
localitiesService
.geocode(request)
.then((localities) => displayLocality(localities.results[0]))
.catch((error) => console.error("Error geocoding localities:", error));
}
}
function displayLocality(locality) {
if (marker) {
marker.setMap(null);
infoWindow.close();
}
if (locality?.geometry) {
marker = new woosmap.map.Marker({
position: locality.geometry.location,
icon: {
url: "https://images.woosmap.com/marker.png",
scaledSize: {
height: 50,
width: 32,
},
},
});
marker.setMap(map);
infoWindow.setContent(`<span>${locality.formatted_address}</span>`);
infoWindow.open(map, marker);
map.setCenter(locality.geometry.location);
renderResponse(locality);
}
}
function escapeHtml(value) {
return value
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function formatNameValue(value) {
return Array.isArray(value) ? value.join(", ") : value;
}
function renderResponse(locality) {
const panel = document.getElementById("response-panel");
const summaryEl = panel?.querySelector(".summary");
const componentsEl = panel?.querySelector(".address-components");
const rawEl = document.getElementById("raw-json");
if (!panel || !summaryEl || !componentsEl || !rawEl) return;
panel.dataset.empty = "false";
const summaryRows = [];
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Formatted address:</span><span class='bold'>${escapeHtml(locality.formatted_address)}</span></p>`,
);
if (locality.types && locality.types.length) {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Types:</span><span class='bold'>${escapeHtml(locality.types.join(", "))}</span></p>`,
);
}
if (locality.public_id) {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Public ID:</span><span class='bold'>${escapeHtml(locality.public_id)}</span></p>`,
);
}
if (typeof locality.distance === "number") {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Distance (m):</span><span class='bold'>${locality.distance}</span></p>`,
);
}
if (locality.geometry) {
const { geometry } = locality;
if (geometry.location_type) {
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Location type:</span><span class='bold'>${escapeHtml(geometry.location_type)}</span></p>`,
);
}
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Latitude:</span><span class='bold'>${geometry.location.lat}</span></p>`,
`<p class='option-detail'><span class='option-detail-label'>Longitude:</span><span class='bold'>${geometry.location.lng}</span></p>`,
);
if (geometry.viewport) {
const { viewport } = geometry;
summaryRows.push(
`<p class='option-detail'><span class='option-detail-label'>Viewport NE:</span><span class='bold'>${viewport.northeast.lat}, ${viewport.northeast.lng}</span></p>`,
`<p class='option-detail'><span class='option-detail-label'>Viewport SW:</span><span class='bold'>${viewport.southwest.lat}, ${viewport.southwest.lng}</span></p>`,
);
}
}
summaryEl.innerHTML = `<div class='section-title'>Summary</div>${summaryRows.join("")}`;
if (locality.address_components && locality.address_components.length) {
const rows = locality.address_components
.map((compo) => {
const label = escapeHtml((compo.types[0] ?? "").replace(/_/g, " "));
const longName = escapeHtml(formatNameValue(compo.long_name));
return `<p class='option-detail'><span class='option-detail-label'>${label}:</span><span class='bold'>${longName}</span></p>`;
})
.join("");
componentsEl.innerHTML = `<div class='section-title'>Address components</div>${rows}`;
} else {
componentsEl.innerHTML = "";
}
rawEl.textContent = JSON.stringify(locality, null, 2);
}
const copyBtn = document.getElementById("copy-raw-json");
if (copyBtn) {
copyBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const rawEl = document.getElementById("raw-json");
const text = rawEl?.textContent ?? "";
if (!text) return;
navigator.clipboard
.writeText(text)
.then(() => {
copyBtn.classList.add("copied");
window.setTimeout(() => copyBtn.classList.remove("copied"), 1500);
})
.catch((err) => console.error("Failed to copy raw JSON:", err));
});
}
function clearResponse() {
const panel = document.getElementById("response-panel");
if (!panel) return;
panel.dataset.empty = "true";
const summaryEl = panel.querySelector(".summary");
const componentsEl = panel.querySelector(".address-components");
const rawEl = document.getElementById("raw-json");
if (summaryEl) summaryEl.innerHTML = "";
if (componentsEl) componentsEl.innerHTML = "";
if (rawEl) rawEl.textContent = "";
}
window.initMap = initMap;
/*
* Always set the map height explicitly to define the size of the div element
* that contains the map.
*/
#map {
height: 100%;
}
/*
* Optional: Makes the sample page fill the window.
*/
html,
body {
height: 100%;
margin: 0;
padding: 0;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}
#autocomplete-container {
display: flex;
position: absolute;
top: 10px;
left: 10px;
z-index: 1;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 -1px 0px rgba(0, 0, 0, 0.02);
background: #fff;
border-radius: 12px;
padding: 0 12px;
max-width: 320px;
width: 100%;
height: 42px;
border: none;
box-sizing: border-box;
align-items: center;
cursor: text;
font-size: 15px;
}
#autocomplete-container .search-icon, #autocomplete-container .clear-icon {
color: inherit;
flex-shrink: 0;
height: 16px;
width: 16px;
}
#autocomplete-container .clear-icon {
transform: scale(1.3);
}
#autocomplete-input {
box-sizing: border-box;
padding: 0;
height: 40px;
line-height: 24px;
vertical-align: top;
transition-property: color;
transition-duration: 0.3s;
width: 100%;
text-overflow: ellipsis;
background: transparent;
border-radius: 0;
border: 0;
margin: 0 8px;
outline: 0;
overflow: visible;
appearance: textfield;
font-size: 100%;
}
.clear-searchButton {
display: none;
height: 18px;
width: 22px;
background: none;
border: none;
vertical-align: middle;
pointer-events: all;
cursor: pointer;
}
#app {
height: 100%;
}
.btn {
background: #3d5afe;
border: 0;
border-radius: 4px;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);
-webkit-transition: background 0.3s, color 0.3s;
transition: background 0.3s, color 0.3s;
box-sizing: border-box;
font-size: 14px;
color: #202124;
cursor: pointer;
display: inline;
font-weight: 600;
height: 38px;
padding: 0 15px;
position: relative;
align-items: center;
}
.btn:hover {
background: rgb(10.2615384615, 46.8461538462, 253.7384615385);
}
.btnText {
color: #fff;
cursor: pointer;
font-size: 0.875rem;
font-weight: 500;
letter-spacing: 0;
line-height: 1.25rem;
}
.btnText:hover {
text-decoration: none;
}
#response-panel {
position: absolute;
right: 10px;
bottom: 25px;
background-color: #fff;
border-radius: 3px;
box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
margin: 10px;
padding: 5px;
overflow: hidden;
z-index: 1;
width: 360px;
max-width: calc(100vw - 40px);
max-height: calc(40vh - 25px);
overflow-y: auto;
padding: 0;
font-size: 13px;
}
#response-panel .panel-header {
padding: 12px 14px;
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
}
#response-panel .panel-title {
font-weight: 700;
font-size: 14px;
margin-bottom: 4px;
}
#response-panel .panel-hint {
color: rgba(0, 0, 0, 0.6);
font-size: 12px;
}
#response-panel .section-title {
color: rgba(0, 0, 0, 0.5);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 1px;
padding: 14px 12px 8px 12px;
}
#response-panel .summary,
#response-panel .address-components {
background-color: #fff;
}
#response-panel .address-components {
background-color: rgba(0, 0, 0, 0.03);
}
#response-panel .option-detail {
display: flex;
flex-wrap: wrap;
padding: 0 12px 8px 12px;
margin: 0;
overflow-wrap: anywhere;
word-break: break-word;
}
#response-panel .option-detail-label {
color: rgba(0, 0, 0, 0.5);
margin-right: 4px;
flex-shrink: 0;
}
#response-panel .bold {
font-weight: 700;
}
#response-panel .raw-json-details {
border-top: 1px solid rgba(0, 0, 0, 0.08);
}
#response-panel .raw-json-details summary {
cursor: pointer;
padding: 10px 14px;
font-weight: 600;
user-select: none;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
#response-panel .raw-json-details .copy-btn {
background: transparent;
border: 0;
padding: 2px 4px;
cursor: pointer;
color: rgba(0, 0, 0, 0.5);
display: inline-flex;
align-items: center;
transition: color 0.2s ease-in-out;
}
#response-panel .raw-json-details .copy-btn:hover, #response-panel .raw-json-details .copy-btn:focus {
color: #3d5afe;
outline: none;
}
#response-panel .raw-json-details .copy-btn .icon-check {
display: none;
color: #2e7d32;
}
#response-panel .raw-json-details .copy-btn.copied {
color: #2e7d32;
}
#response-panel .raw-json-details .copy-btn.copied .icon-copy {
display: none;
}
#response-panel .raw-json-details .copy-btn.copied .icon-check {
display: inline-block;
}
#response-panel .raw-json-details pre {
margin: 0 10px 10px 10px;
padding: 10px;
border: 1px solid #e0e0e0;
background-color: #fafafa;
border-radius: 6px;
white-space: pre-wrap;
overflow-x: auto;
font-size: 12px;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
#response-panel[data-empty=true] .summary,
#response-panel[data-empty=true] .address-components,
#response-panel[data-empty=true] .raw-json-details {
display: none;
}
<html>
<head>
<title>Localities Geocode</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="app">
<div id="autocomplete-container">
<svg class="search-icon" viewBox="0 0 16 16">
<path
d="M3.617 7.083a4.338 4.338 0 1 1 8.676 0 4.338 4.338 0 0 1-8.676 0m4.338-5.838a5.838 5.838 0 1 0 2.162 11.262l2.278 2.279a1 1 0 0 0 1.415-1.414l-1.95-1.95A5.838 5.838 0 0 0 7.955 1.245"
fill-rule="evenodd"
clip-rule="evenodd"
></path>
</svg>
<input
type="text"
id="autocomplete-input"
placeholder="Geocode Localities..."
/>
<button aria-label="Clear" class="clear-searchButton" type="button">
<svg class="clear-icon" viewBox="0 0 24 24">
<path
d="M7.074 5.754a.933.933 0 1 0-1.32 1.317L10.693 12l-4.937 4.929a.931.931 0 1 0 1.319 1.317l4.938-4.93 4.937 4.93a.933.933 0 0 0 1.581-.662.93.93 0 0 0-.262-.655L13.331 12l4.937-4.929a.93.93 0 0 0-.663-1.578.93.93 0 0 0-.656.261l-4.938 4.93z"
></path>
</svg>
</button>
</div>
<aside id="response-panel" data-empty="true">
<div class="panel-header">
<div class="panel-title">Geocode response</div>
<div class="panel-hint">
Enter an address to geocode or click on the map to reverse geocode.
</div>
</div>
<div class="summary"></div>
<div class="address-components"></div>
<details class="raw-json-details">
<summary>
<span>Raw JSON</span>
<button
id="copy-raw-json"
class="copy-btn"
type="button"
title="Copy"
aria-label="Copy raw JSON"
>
<svg
class="icon-copy"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width="16"
height="16"
>
<path
fill="currentColor"
d="m18.6 7.494-.625-.112a20.62 20.62 0 0 0-2.261-.264V4.982A2.328 2.328 0 0 0 13.8 2.688l-.626-.113a20.28 20.28 0 0 0-7.188 0l-.624.113A2.327 2.327 0 0 0 3.44 4.982v8.885a2.331 2.331 0 0 0 2.742 2.295 19.243 19.243 0 0 1 2.065-.244v2.756a2.329 2.329 0 0 0 2.742 2.294 19.142 19.142 0 0 1 6.793 0 2.33 2.33 0 0 0 2.742-2.294V9.789A2.33 2.33 0 0 0 18.6 7.494zM5.985 15.059a1.211 1.211 0 0 1-1.425-1.192V4.982a1.209 1.209 0 0 1 1-1.192l.624-.112a19.142 19.142 0 0 1 6.793 0l.625.112a1.211 1.211 0 0 1 1 1.192v8.885a1.213 1.213 0 0 1-1.426 1.192 20.358 20.358 0 0 0-4.293-.29.54.54 0 0 0-.072-.014.54.54 0 0 0-.113.023 20.3 20.3 0 0 0-2.713.281zM19.4 18.674a1.211 1.211 0 0 1-1.425 1.192 20.275 20.275 0 0 0-7.187 0A1.222 1.222 0 0 1 9.8 19.6a1.209 1.209 0 0 1-.434-.929v-2.803a19.126 19.126 0 0 1 3.608.294 2.409 2.409 0 0 0 .413.036 2.332 2.332 0 0 0 2.33-2.331V8.24a19.561 19.561 0 0 1 2.064.245l.625.112a1.209 1.209 0 0 1 1 1.192z"
></path>
</svg>
<svg
class="icon-check"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 13 9"
width="14"
height="10"
fill="none"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M12.026 0.188287C12.2771 0.439342 12.2771 0.846374 12.026 1.09743L4.31172 8.81172C4.06067 9.06276 3.65363 9.06276 3.40258 8.81172L0.188287 5.59743C-0.0627622 5.3464 -0.0627622 4.93934 0.188287 4.6883C0.439342 4.43726 0.846374 4.43726 1.09743 4.6883L3.85715 7.44803L11.1169 0.188287C11.3679 -0.0627622 11.775 -0.0627622 12.026 0.188287Z"
fill="currentColor"
></path>
</svg>
</button>
</summary>
<pre><code id="raw-json"></code></pre>
</details>
</aside>
<div id="map"></div>
</div>
<script
src="https://sdk.woosmap.com/map/map.js?key=woos-48c80350-88aa-333e-835a-07f4b658a9a4&callback=initMap"
defer
></script>
</body>
</html>
Running the Sample Locally
Before you can run this sample on your local machine, you need to have Git and Node.js installed. If they’re not already installed, follow these instructions to get them set up.
Once you have Git and Node.js installed, you can run the sample by following these steps:
-
Clone the repository and navigate to the directory of the sample.
-
Install the necessary dependencies.
-
Start running the sample.
Here are the commands you can use in your terminal to do this:
git clone -b sample/localities-geocode https://github.com/woosmap/js-samples.git
cd js-samples
npm i
npm start
You can experiment with other samples by switching to any branch that starts with the pattern sample/SAMPLE_NAME.
git checkout sample/SAMPLE_NAME
npm i
npm start