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