Add Geocoder to a Web Map
This example adds a MapboxGeocoder control to a Mapbox GL JS web map, enabling users to search the map for a place. After the user chooses a suggestion, a Marker is added to the map and the camera moves to the selected location.
Setting the Geocoder options
allows for control of the search results. proximity
is used to list results by proximity to the center of the map. Explore all MapboxGeocoder options.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add Geocoder to a Web Map</title>
<!-- Default styling. Feel free to remove! -->
<link href="https://api.mapbox.com/mapbox-assembly/v1.3.0/assembly.min.css" rel="stylesheet">
<script id="search-js" defer="" src="https://api.mapbox.com/search-js/v1.0.0-beta.22/web.js"></script>
</head>
<body>
<!-- Load Mapbox GL JS -->
<link href="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>
<div id="map" style="position: absolute; width: 100%; height: 100%"></div>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';
mapboxgl.accessToken = ACCESS_TOKEN;
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [-73.99209, 40.68933],
zoom: 8.8
});
const searchJS = document.getElementById('search-js');
searchJS.onload = function () {
const geocoder = new MapboxGeocoder();
geocoder.accessToken = ACCESS_TOKEN;
geocoder.options = {
proximity: [-73.99209, 40.68933]
};
geocoder.marker = true;
geocoder.mapboxgl = mapboxgl;
map.addControl(geocoder);
};
</script>
</body>
</html>
このexampleは役に立ちましたか?