admin管理员组

文章数量:1402288

I've been adding custom markers to a Mapbox map, which is fine and working with no trouble, and previously I've used popups, which have also worked fine e.g.:

.setPopup(new mapboxgl.Popup({ offset: 30 }) // add popups
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))

But I want to just find a way to add an onclick function to the markers instead. I've tried a number of different methods, but I can't get anything to work. I'm assuming something along the lines of:

marker.on('click', function(e) {
  alert("test");
})

but it's just not cutting it. I've tried a few different options, but I'm ing up blank.

This is how markers are added to the map:

var geojson = {

type: 'FeatureCollection',
  features: [{
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-2.24, 53.48]
    },
    properties: {
      title: 'manchester',
      description: '<title class="info" onclick="opendiv()">Manchester</title>',
      id: '#manchester'
    }
  },
]};

// add markers to map
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'pin';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el, {
  offset: [0, -15]
})
.setLngLat(marker.geometry.coordinates)
//popup was previously here
.addTo(featuremap);
});

Any advice would be much appreciated!

I've included the rest of the related code in snippets, in case it's useful.

mapboxgl.accessToken = '###########';

var featuremap= new mapboxgl.Map({
      container: 'featuremap',
      style: 'mapbox://styles/mapbox/basic-v9',
      center: [-3.9,54.7],
      zoom: 4.5

     });

     /* given a query returns a matching geographic coordinates as search results in
      * carmen geojson format, .md
      */
     var coordinatesGeocoder = function (query) {
             // match anything which looks like a decimal degrees coordinate pair
         var matches = query.match(/^[ ]*(-?\d+\.?\d*)[, ]+(-?\d+\.?\d*)[ ]*$/);
         if (!matches) {
             return null;
         }

         function coordinateFeature(lng, lat) {
             return {
                 center: [lng, lat],
                 geometry: {
                     type: "Point",
                     coordinates: [lng, lat]
                 },
                 place_name: 'Lat: ' + lat + ', Lng: ' + lng, // eslint-disable-line camelcase
                 place_type: ['coordinate'], // eslint-disable-line camelcase
                 properties: {},
                 type: 'Feature'
             };
         }

         var coord1 = Number(matches[1]);
         var coord2 = Number(matches[2]);
         var geocodes = [];

         if (coord1 < -90 || coord1 > 90) {
             // must be lng, lat
             geocodes.push(coordinateFeature(coord1, coord2));
         }

         if (coord2 < -90 || coord2 > 90) {
             // must be lat, lng
             geocodes.push(coordinateFeature(coord2, coord1));
         }

         if (geocodes.length === 0) {
             // else could be either lng, lat or lat, lng
             geocodes.push(coordinateFeature(coord1, coord2));
             geocodes.push(coordinateFeature(coord2, coord1));
         }

         return geocodes;
     };

     map.addControl(new MapboxGeocoder({
         accessToken: mapboxgl.accessToken,
         localGeocoder: coordinatesGeocoder
     }));
.pin {
  background-image: url('../images/marker.png');
  background-size: cover;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;

}
<script src='.44.1/mapbox-gl.js'></script>
    <link href='.44.1/mapbox-gl.css' rel='stylesheet' />

...

I've been adding custom markers to a Mapbox map, which is fine and working with no trouble, and previously I've used popups, which have also worked fine e.g.:

.setPopup(new mapboxgl.Popup({ offset: 30 }) // add popups
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))

But I want to just find a way to add an onclick function to the markers instead. I've tried a number of different methods, but I can't get anything to work. I'm assuming something along the lines of:

marker.on('click', function(e) {
  alert("test");
})

but it's just not cutting it. I've tried a few different options, but I'm ing up blank.

This is how markers are added to the map:

var geojson = {

type: 'FeatureCollection',
  features: [{
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-2.24, 53.48]
    },
    properties: {
      title: 'manchester',
      description: '<title class="info" onclick="opendiv()">Manchester</title>',
      id: '#manchester'
    }
  },
]};

// add markers to map
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'pin';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el, {
  offset: [0, -15]
})
.setLngLat(marker.geometry.coordinates)
//popup was previously here
.addTo(featuremap);
});

Any advice would be much appreciated!

I've included the rest of the related code in snippets, in case it's useful.

mapboxgl.accessToken = '###########';

var featuremap= new mapboxgl.Map({
      container: 'featuremap',
      style: 'mapbox://styles/mapbox/basic-v9',
      center: [-3.9,54.7],
      zoom: 4.5

     });

     /* given a query returns a matching geographic coordinates as search results in
      * carmen geojson format, https://github./mapbox/carmen/blob/master/carmen-geojson.md
      */
     var coordinatesGeocoder = function (query) {
             // match anything which looks like a decimal degrees coordinate pair
         var matches = query.match(/^[ ]*(-?\d+\.?\d*)[, ]+(-?\d+\.?\d*)[ ]*$/);
         if (!matches) {
             return null;
         }

         function coordinateFeature(lng, lat) {
             return {
                 center: [lng, lat],
                 geometry: {
                     type: "Point",
                     coordinates: [lng, lat]
                 },
                 place_name: 'Lat: ' + lat + ', Lng: ' + lng, // eslint-disable-line camelcase
                 place_type: ['coordinate'], // eslint-disable-line camelcase
                 properties: {},
                 type: 'Feature'
             };
         }

         var coord1 = Number(matches[1]);
         var coord2 = Number(matches[2]);
         var geocodes = [];

         if (coord1 < -90 || coord1 > 90) {
             // must be lng, lat
             geocodes.push(coordinateFeature(coord1, coord2));
         }

         if (coord2 < -90 || coord2 > 90) {
             // must be lat, lng
             geocodes.push(coordinateFeature(coord2, coord1));
         }

         if (geocodes.length === 0) {
             // else could be either lng, lat or lat, lng
             geocodes.push(coordinateFeature(coord1, coord2));
             geocodes.push(coordinateFeature(coord2, coord1));
         }

         return geocodes;
     };

     map.addControl(new MapboxGeocoder({
         accessToken: mapboxgl.accessToken,
         localGeocoder: coordinatesGeocoder
     }));
.pin {
  background-image: url('../images/marker.png');
  background-size: cover;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;

}
<script src='https://api.tiles.mapbox./mapbox-gl-js/v0.44.1/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox./mapbox-gl-js/v0.44.1/mapbox-gl.css' rel='stylesheet' />

...

Share Improve this question asked Feb 5, 2020 at 22:33 HannahHannah 311 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

An update on this question that may potentially help those that don't want to add additional MapBox layers is to just use the getElement() method on the mapboxgl.Marker object and attach the click event listener to that.

Ex:

// Create new marker
var marker = new mapboxgl.Marker(el).setLngLat([0,0]).addTo(map);

// Attach event listener to raw HTML element
marker.getElement().addEventListener('click', (e) => console.log(e));

You will want to add a layer for the markers and then target the click event to that layer. Mapbox has an example of this on their website here. I've added the relevant portion here:

map.addLayer({
  'id': 'places',
  'type': 'symbol',
  'source': 'places', // Your Geojson, added as a [Source][4]
  'layout': {
    'icon-image': '{icon}-15',
    'icon-allow-overlap': true
  }
});

map.on('click', 'places', function(e) {
  var coordinates = e.features[0].geometry.coordinates.slice();
  var description = e.features[0].properties.description;

  // Ensure that if the map is zoomed out such that multiple
  // copies of the feature are visible, the popup appears
  // over the copy being pointed to.
  while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
    coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
  }

new mapboxgl.Popup()
  .setLngLat(coordinates)
  .setHTML(description)
  .addTo(map);
});

I had the same issue. This solved the problem. Make sure to add the jQuery CDN

//from dev tools I got the class name of the marker div 
$(document).on('click', '.mapboxgl-marker', function() {
  console.log("hello");
});

本文标签: javascriptAdd onclick to a Mapbox marker elementStack Overflow