Source: https://developers.woosmap.com/js-samples/geolocation-api/

> For clean Markdown of any page, append `.md` to the page URL.

> For a complete documentation index, see https://developers.woosmap.com/llms.txt

# Geolocation Api



## Example

https://demo.woosmap.com/js-samples/samples/geolocation-api/app/dist/
[](https://demo.woosmap.com/js-samples/samples/geolocation-api/highlight/highlight.html "Open in new tab with highlighted code")
Try sample 

- [CodeSandbox](https://codesandbox.io/p/devbox/github/woosmap/js-samples/tree/master/dist/samples/geolocation-api/app?file=index.ts)
- [JsFiddle](https://jsfiddle.net/gh/get/library/pure/woosmap/js-samples/tree/master/dist/samples/geolocation-api/jsfiddle)
- [Clone on Github](https://github.com/Woosmap/js-samples/tree/sample/geolocation-api)

```typescript
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;
}

function initMap(): void {
  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 = new woosmap.map.Map(document.getElementById("map") as HTMLElement, {
    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 marker = new woosmap.map.Marker({
    position: userPosition,
    icon: {
      url: "https://images.woosmap.com/user-position-small.png",
    },
  });
  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, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
  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);
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;
```

```javascript
let map;
const woosmap_key = "YOUR_API_KEY";

function initMap() {
  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 = new woosmap.map.Map(document.getElementById("map"), {
    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 marker = new woosmap.map.Marker({
    position: userPosition,
    icon: {
      url: "https://images.woosmap.com/user-position-small.png",
    },
  });

  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, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
  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);
}

window.initMap = initMap;
```

```css
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
<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>
      <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](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) to get them set up.

Once you have Git and Node.js installed, you can run the sample by following these steps:

1. Clone the repository and navigate to the directory of the sample.

2. Install the necessary dependencies.

3. Start running the sample.

Here are the commands you can use in your terminal to do this:

```shell
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`.

```shell
git checkout sample/SAMPLE_NAME
npm i
npm start
```
