javascriptjquerymapboxmapbox-gl-jsmapbox-marker

How set marker on click when map load - Mapbox GLJS


I've made a MapBox for get Current Coordinate for Gmaps :

mapboxgl.accessToken ='pk.eyJ1IjoibW5hdWZhbGF6a2lhIiwiYSI6ImNrcWV4MzN0ZDA2NjQyd2xrazhhbG96eHMifQ.3R_B2O8m_CQ_tERmmji8mA';
    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [107.138013,-6.814071],
        zoom: 13,
    });
    
    // Add the control to the map.
    var geocoder = new MapboxGeocoder({
        accessToken: mapboxgl.accessToken,
        marker: false,
        mapboxgl: mapboxgl
    });

document.getElementById('geocoder').appendChild(geocoder.onAdd(map));


geocoder.on('result', function(r) {
    document.getElementById("maps").value = r.result.center;
    var reverse = document.getElementById("maps").value;
    reverse = reverse.split(",");
    var latitude = reverse[1];
    var longitude = reverse[0];
    document.getElementById("maps").value = latitude + "," + longitude;
  
    var marker1 = new mapboxgl.Marker({ draggable: false, color: "blue" })
    .setLngLat(r.result.center)
    .addTo(map);
    map.flyTo({
    center: r.result.center,
    zoom:15,
    speed:5,
    });
    map.on('click', function(e) {
            var coordinates = e.lngLat;
        var popup = new mapboxgl.Popup()
        .setLngLat(coordinates)
        .setHTML('MapBox Coordinate<br/>' + coordinates)
        .addTo(map);
        marker1.setLngLat(coordinates)
        marker1.setPopup(popup)
        map.flyTo({
        center: coordinates,
        zoom:15,
        speed:5,
        });
      document.getElementById("maps").value = coordinates;
      var lokasi = $('#maps').val().replace(/[^0-9,.-]/ig, "");
      $('#maps').val(lokasi);
      var reverse = document.getElementById("maps").value;
      reverse = reverse.split(",");
      var latitude = reverse[1];
      var longitude = reverse[0];
      document.getElementById("maps").value = latitude + "," + longitude;
          });
});

$('#modalrubahlokasi').on('shown.bs.modal', function() {
    map.resize();
});

document.querySelector('.mapboxgl-ctrl-geocoder input').placeholder = "Search Location Here";

Here's codepen links : https://codepen.io/mnaufalazkia/pen/wvdwmoY

But I can't set marker when i click the map before i've search the location first.

But i've tried map.on('load' function and add map.on('click' for map load function for set marker, but not working properly. but when i search the location first, and click the maps, the marker working properly.

Someone can help me to add marker when i click the map, just like when i search the location first, but of course remove the previous marker. Thank You


Solution

  • A lot of the following suggestions came from retooling of these resources:

    You can achieve setting a marker when you click the map before searching the location by adding markers to the map independently of the geocoder after the map has been initialized by:

    map.on('click', function add_marker (event) {
      var coordinates = event.lngLat;
      console.log('Lng:', coordinates.lng, 'Lat:', coordinates.lat), 'id', event.id;
      marker.setLngLat(coordinates).addTo(map);
    // 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(event.lngLat.lng - coordinates[0]) > 180) {
    coordinates[0] += event.lngLat.lng > coordinates[0] ? 360 : -360;
    }
    var popup = new mapboxgl.Popup({ offset: 35 })
    .setLngLat(coordinates)
            .setHTML('MapBox Coordinate<br/>' + coordinates)
            .addTo(map)
    })

    Then you can handle your popups within your geocoder to close out when you click away. There isn't a need to call a map.on('click') again here.

    geocoder.on('result', function(r) {
        document.getElementById("maps").value = r.result.center;
        var reverse = document.getElementById("maps").value;
       
        var latitude = reverse[1];
        var longitude = reverse[0];
        document.getElementById("maps").value = latitude + "," + longitude;
      
        var marker1 = new mapboxgl.Marker({ draggable: false, color: "blue"})
        .setLngLat(r.result.center)
        .addTo(map);
        map.flyTo({
        center: r.result.center,
        zoom:15,
        speed:5,
        })
        
        new mapboxgl.Popup({offset: 35, closeOnClick: true})
            .setLngLat(r.result.center)
            .setHTML('MapBox Coordinate<br/>' + r.result.center)
            .addTo(map);
        map.on('click', function(){
            marker1.remove();
        })
    });

    Here is a working example in a jsfiddle: https://jsfiddle.net/jameslcarpino/gchsvoxL/1/