Geolocation Api
Get location of a user’s device from its ip address
Example
Geolocation Api
let map: woosmap.map.Map;
const woosmap_key = "YOUR_API_KEY";
interface GeoLocationResponse {
accuracy: number;
continent: string;
country_code: string;
country_name: string;
latitude: number;
longitude: number;
postal_code: string;
region_state: string;
timezone: string;
viewport: Bounds;
city: string;
}
interface Bounds {
northeast: woosmap.map.LatLngLiteral;
southwest: woosmap.map.LatLngLiteral;
}
async function initMap(): Promise<void> {
await woosmap.map.importLibrary("maps");
await woosmap.map.importLibrary("marker");
fetch(`https://api.woosmap.com/geolocation/position/?key=${woosmap_key}`)
.then((result) => {
return result.json();
})
.then((position: GeoLocationResponse) => {
renderUserLocationOnMap(position);
displayGeolocationResponse(position);
});
}
function renderUserLocationOnMap({ latitude, accuracy, longitude, viewport }) {
const userPosition: woosmap.map.LatLngLiteral = {
lat: latitude,
lng: longitude,
};
let zoom = 12;
if (accuracy > 200) {
zoom = 4;
} else if (accuracy > 50) {
zoom = 5;
} else if (accuracy > 25) {
zoom = 8;
} else if (accuracy > 10) {
zoom = 9;
} else if (accuracy > 5) {
zoom = 10;
} else if (accuracy > 1) {
zoom = 11;
}
map = (document.getElementById("map") as woosmap.map.MapElement).innerMap;
map.moveCamera({ center: userPosition, zoom });
if (viewport) {
const bounds = {
east: viewport.northeast.lng,
south: viewport.southwest.lat,
north: viewport.northeast.lat,
west: viewport.southwest.lng,
};
map.fitBounds(bounds);
plotBoundary(bounds);
}
const markerContent = document.createElement("img");
markerContent.src = "https://images.woosmap.com/user-position-small.png";
const marker = new woosmap.map.marker.AdvancedMarkerElement({
position: userPosition,
content: markerContent,
});
marker.setMap(map);
}
function displayGeolocationResponse(position: GeoLocationResponse) {
const html: string[] = [];
html.push(syntaxHighlight(position));
const $infoContainer = document.getElementById("response") as HTMLElement;
if ($infoContainer) {
$infoContainer.innerHTML = html.join("");
$infoContainer.style.display = "block";
}
}
function syntaxHighlight(json): string {
if (typeof json != "string") {
json = JSON.stringify(json, undefined, 2);
}
json = json
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
return json.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\\-]?\d+)?)/g,
(match) => {
let cls = "number";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "key";
} else {
cls = "string";
}
} else if (/true|false/.test(match)) {
cls = "boolean";
} else if (/null/.test(match)) {
cls = "null";
}
return '<span class="' + cls + '">' + match + "</span>";
},
);
}
function plotBoundary(bounds: woosmap.map.LatLngBoundsLiteral): void {
const rectangle = new woosmap.map.Rectangle({
bounds,
strokeColor: "#b71c1c",
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: "#b71c1c",
fillOpacity: 0.2,
});
rectangle.setMap(map);
}
initMap();
let map;
const woosmap_key = "YOUR_API_KEY";
async function initMap() {
await woosmap.map.importLibrary("maps");
await woosmap.map.importLibrary("marker");
fetch(`https://api.woosmap.com/geolocation/position/?key=${woosmap_key}`)
.then((result) => {
return result.json();
})
.then((position) => {
renderUserLocationOnMap(position);
displayGeolocationResponse(position);
});
}
function renderUserLocationOnMap({ latitude, accuracy, longitude, viewport }) {
const userPosition = {
lat: latitude,
lng: longitude,
};
let zoom = 12;
if (accuracy > 200) {
zoom = 4;
} else if (accuracy > 50) {
zoom = 5;
} else if (accuracy > 25) {
zoom = 8;
} else if (accuracy > 10) {
zoom = 9;
} else if (accuracy > 5) {
zoom = 10;
} else if (accuracy > 1) {
zoom = 11;
}
map = document.getElementById("map").innerMap;
map.moveCamera({ center: userPosition, zoom });
if (viewport) {
const bounds = {
east: viewport.northeast.lng,
south: viewport.southwest.lat,
north: viewport.northeast.lat,
west: viewport.southwest.lng,
};
map.fitBounds(bounds);
plotBoundary(bounds);
}
const markerContent = document.createElement("img");
markerContent.src = "https://images.woosmap.com/user-position-small.png";
const marker = new woosmap.map.marker.AdvancedMarkerElement({
position: userPosition,
content: markerContent,
});
marker.setMap(map);
}
function displayGeolocationResponse(position) {
const html = [];
html.push(syntaxHighlight(position));
const $infoContainer = document.getElementById("response");
if ($infoContainer) {
$infoContainer.innerHTML = html.join("");
$infoContainer.style.display = "block";
}
}
function syntaxHighlight(json) {
if (typeof json != "string") {
json = JSON.stringify(json, undefined, 2);
}
json = json
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
return json.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\\-]?\d+)?)/g,
(match) => {
let cls = "number";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "key";
} else {
cls = "string";
}
} else if (/true|false/.test(match)) {
cls = "boolean";
} else if (/null/.test(match)) {
cls = "null";
}
return '<span class="' + cls + '">' + match + "</span>";
},
);
}
function plotBoundary(bounds) {
const rectangle = new woosmap.map.Rectangle({
bounds,
strokeColor: "#b71c1c",
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: "#b71c1c",
fillOpacity: 0.2,
});
rectangle.setMap(map);
}
initMap();
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;
}
#container {
height: 100%;
display: flex;
}
#sidebar {
flex-basis: 12rem;
flex-grow: 1;
max-width: 30rem;
height: 100%;
box-sizing: border-box;
overflow: auto;
}
#map {
flex-basis: 70vw;
flex-grow: 5;
height: 100%;
}
#sidebar {
padding: 5px;
flex-basis: 25rem;
}
pre .string {
color: green;
}
pre .number {
color: magenta;
}
pre .boolean {
color: blue;
}
pre .null {
color: magenta;
}
pre .key {
color: #1D1D1D;
}
<html>
<head>
<title>Geolocation Api</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>
<!--The div element for the map -->
<div id="container">
<div id="sidebar">
<strong>Geolocation API Response</strong>
<pre id="response"></pre>
</div>
<wmp-map id="map"></wmp-map>
</div>
<script>
(g=>{var p,w=window,d=document,l="importLibrary",q="__ib__",e="The Woosmap Maps JavaScript API",o=w.woosmap||(w.woosmap={}),m=o.map||(o.map={}),r=new Set(String(g.libraries||"").split(",").filter(Boolean)),s=new URLSearchParams,u=()=>p||(p=new Promise((f,n)=>{var a=d.createElement("script");s.set("libraries",[...r]+"");for(var k in g)k!="libraries"&&g[k]&&s.set(k,g[k]);s.set("callback","woosmap.map."+q);a.src="https://sdk.woosmap.com/map/map.js?"+s;m[q]=f;a.onerror=()=>n(Error(e+" could not load."));a.nonce=d.querySelector("script[nonce]")?.nonce||"";d.head.append(a)}));m[l]?console.warn(e+" only loads once. Ignoring:",g):m[l]=(f,...n)=>r.add(f)&&u().then(()=>m[l](f,...n))})({
key: "woos-e1e5490b-19d1-34f8-9955-fd5cfc8c880f",
libraries: "marker",
});
</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/geolocation-api 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