|
| 1 | +--- |
| 2 | +layout: example |
| 3 | +category: example |
| 4 | +title: Set a point after Geocoder result |
| 5 | +description: 'Listen to the <code>geocoder.input</code> event from the <a target="_blank" href="https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-geocoder">Geocoder plugin</a> and place a point on the coordinate results.' |
| 6 | +tags: |
| 7 | + - plugins |
| 8 | + - mapbox-geocoding |
| 9 | +--- |
| 10 | +<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v0.1.0/mapbox-gl-geocoder.js'></script> |
| 11 | +<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v0.1.0/mapbox-gl-geocoder.css' type='text/css' /> |
| 12 | +<style> |
| 13 | +#geocoder-container { |
| 14 | + position: absolute; |
| 15 | + top: 0; |
| 16 | + width: 100%; |
| 17 | + margin-top: 10px; |
| 18 | +} |
| 19 | + |
| 20 | +#geocoder-container > div { |
| 21 | + min-width:50%; |
| 22 | + margin-left:25%; |
| 23 | +} |
| 24 | +</style> |
| 25 | +<div id='map'></div> |
| 26 | +<div id='geocoder-container'></div> |
| 27 | + |
| 28 | +<script> |
| 29 | +var map = new mapboxgl.Map({ |
| 30 | + container: 'map', |
| 31 | + style: 'mapbox://styles/mapbox/streets-v8', |
| 32 | + center: [-79.4512, 43.6568], |
| 33 | + zoom: 13 |
| 34 | +}); |
| 35 | + |
| 36 | +var geocoder = new mapboxgl.Geocoder({ |
| 37 | + container: 'geocoder-container' // Optional. Specify a unique container for the control to be added to. |
| 38 | +}); |
| 39 | + |
| 40 | +map.addControl(geocoder); |
| 41 | + |
| 42 | +// After the map style has loaded on the page, add a source layer and default |
| 43 | +// styling for a single point. |
| 44 | +map.on('style.load', function() { |
| 45 | + map.addSource('single-point', { |
| 46 | + "type": "geojson", |
| 47 | + "data": { |
| 48 | + "type": "FeatureCollection", |
| 49 | + "features": [] |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | + map.addLayer({ |
| 54 | + "id": "point", |
| 55 | + "source": "single-point", |
| 56 | + "type": "circle", |
| 57 | + "paint": { |
| 58 | + "circle-radius": 10, |
| 59 | + "circle-color": "#007cbf" |
| 60 | + } |
| 61 | + }); |
| 62 | + |
| 63 | + // Listen for the `geocoder.input` event that is triggered when a user |
| 64 | + // makes a selection and add a marker that matches the result. |
| 65 | + geocoder.on('geocoder.input', function(ev) { |
| 66 | + map.getSource('single-point').setData(ev.result.geometry); |
| 67 | + }); |
| 68 | +}); |
| 69 | +</script> |
0 commit comments