I'm using TomTom Map SDK in NextJs to create functionality such that when map is loaded based on the map bounds, i query all the nearby restaurants in that area. And on map zoom or drag event i want to call the api again with new bounds to update the restaurants list.
Here's my component:
import React, { useEffect, useRef, useState } from "react";
import * as tt from "@tomtom-international/web-sdk-maps";
import "@tomtom-international/web-sdk-maps/dist/maps.css";
function Map() {
const mapElement = useRef();
const [map, setMap] = useState({});
const [longitude, setLongitude] = useState(21.112869);
const [latitude, setLatitude] = useState(51.504);
useEffect(() => {
let map = tt.map({
key: "MY_MAP_KEY",
container: mapElement.current,
stylesVisibility: {
trafficIncidents: true,
trafficFlow: true,
},
center: [longitude, latitude],
zoom: 14,
});
console.log(map.getBounds().getNorthEast().lat);
const addMarker = () => {
let div = document.createElement("div");
div.innerHTML = `Hello There!`;
const size = 50;
const popup = new tt.Popup({
closeButton: false,
offset: size / 2,
anchor: "bottom",
}).setDOMContent(div);
const marker = new tt.Marker()
.setLngLat([longitude, latitude])
.setPopup(popup)
.addTo(map);
};
addMarker();
return () => map.remove();
}, [longitude, latitude]);
return (
<>
{map && (
<div ref={mapElement} className="map" />
)}
</>
);
}
export default Map;
I can across this but it doesn't work! Not sure if such event exists.
window.addEventListener("ns-bridge-ready", function (e) {
var nsWebViewBridge = e.detail || window.nsWebViewBridge;
map.on("dragend", function () {
console.log(map.getBounds().getNorthEast().lat, "nj");
// let center = map.getCenter();
// nsWebViewBridge.emit("mapCenterChanged",
// center.lng.toFixed(3) + ", " + center.lat.toFixed(3));
});
});
window.addEventListener("dragend", (e) => {
console.log(e, "jfdsf");
});
Alright just found the solution. For anyone struggling with the same, You can just use map.on("dragend", callbackFunc) directly inside useEffect and that would call the function everytime there's a drag event end. The best solution that worked for me is using "moveend"
map.on("moveend", () => {
console.log(map.getBounds().getNorthEast().lat, map.getBounds().getNorthEast().lng); });