blog.itcode.devblog.itcode.dev

A Guide for Developers Traveling Through OpenLayers - 13. Collecting the User's Location Information in the Browser

Among map services, some analyze the user's location and present content more appropriate to that location. For example, delivery apps preferentially show only restaurants within a certain range based on the user's location. For applications, the GPS of the smartphone, the primary device they run on, can be leveraged. Similarly, browsers can themselves collect and use location information with the user's consent. Naturally, an internet connection is required.

A Guide for Developers Traveling Through OpenLayers - 13. Collecting the User's Location Information in the Browser

Among map services, some analyze the user's location and present content more appropriate to that location. For example, delivery apps preferentially show only restaurants within a certain range based on the user's location. For applications, the GPS of the smartphone, the primary device they run on, can be leveraged. Similarly, browsers can themselves collect and use location information with the user's consent. Naturally, an internet connection is required.
RWB0104
@RWBwritten at 2022-04-02 17:50:05
A Guide for Developers Traveling Through OpenLayers

시리즈 모아보기

A Guide for Developers Traveling Through OpenLayers

13 / 23

Among map services, some analyze the user's location and present content more appropriate to that location.

For example, delivery apps preferentially show only restaurants within a certain range based on the user's location.

For applications, the GPS of the smartphone, the primary device they run on, can be leveraged. Similarly, browsers can themselves collect and use location information with the user's consent. Naturally, an internet connection is required.

🔐 For the user's security!
For the user's security, elements that can occur without user action, such as personal information or notifications, must always obtain the user's permission. If there is no permission, it will not work.

The feature that collects the user's location in a browser is named Geolocation.

Geolocation collects the location from the user's internet information and returns it in latitude/longitude coordinates (EPSG:4326). Since there's no other option for the coordinate value, if you want to use a different coordinate system, you need to convert appropriately.



There's a possibility of differences between browsers. This document is written based on Chrome.

TYPESCRIPT

import { Map } from 'ol';

/**
 * Method to call geolocation
 * 
 * @param {Map} map: map object
 */
function callGeolocation(map: Map)
{
	// If geolocation is available
	if ('geolocation' in navigator)
	{
		navigator.geolocation.getCurrentPosition(position =>
		{
			const { latitude, longitude } = position.coords;

			map.getView().setCenter([ longitude, latitude ])
		}, () => alert('실패'), { enableHighAccuracy: true });
	}

	// Otherwise
	else
	{
		alert('사용자 위치를 확인할 수 없습니다.');
	}
}
  • getCurrentPosition(success, error, options): A method of the Geolocation object that returns the current position
    • success: success callback
    • error: error callback (can be omitted)
    • options: options object (can be omitted)
  • setCenter(coord): A method that sets the center of the currently viewed map
    • coord: xx, yy coordinates (for lat/long, this is long, lat)

You can use it as above. It checks whether geolocation can be used from the navigator object, and if so, it displays the location using it.




Let's create a button component that moves to the current location. We can place a button at an appropriate location on the map, and configure it so that clicking the button uses geolocation to move to that location.

TSX

interface SubProps
{
	map?: Map
}

/**
 * Method that returns the location button JSX
 *
 * @param {SubProps} props: properties
 *
 * @returns {JSX.Element | null} JSX
 */
export function Location({ map }: SubProps)
{
	// If the map object is valid
	if (map)
	{
		const onClick = () =>
		{
			// If geolocation is available
			if ('geolocation' in navigator)
			{
				navigator.geolocation.getCurrentPosition(position =>
				{
					const { latitude, longitude } = position.coords;

					map.getView().setCenter([ longitude, latitude ]);
				}, () => alert('실패'), { enableHighAccuracy: true });
			}

			// Otherwise
			else
			{
				alert('사용자 위치를 확인할 수 없습니다.');
			}
		};

		return (
			<button className='location' onClick={onClick}>현재 위치</button>
		);
	}

	// Otherwise
	else
	{
		return null;
	}
}

This project is configured in a similar way to the above.

TSX

<Location map={mapState} />

Usage is as above. If map is not specified as a property, it's configured to return null so the button isn't displayed. Since there's no way to move the map without a Map object anyway, it would be useless.


This feature is implemented as the Location sub-component of the project's MapInteraction component.




You can check an example implementing this at OpenLayers6 Sandbox - Geolocation.

Click the green button in the bottom-left to move to the user's location.

Depending on your internet line configuration, note that sometimes the physical location of the line's server shows up instead of the user's actual location.

Mobile internet such as LTE or 5G doesn't have this issue, but with wired internet like LAN, it's not uncommon for the server's location to show up instead of your own on occasion.

# GIS# OpenLayers
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08