Как я уже сказал в своем комментарии, вы можете сделать это наоборот.Извлекать только те маркеры, которые видны в области просмотра карты.Вам просто нужно немного реорганизовать свой код и изменить запрос к базе данных.
Вам необходимо передать минимальную и максимальную широту и долготу вашему контроллеру, чтобы вы могли запросить в БД маркеры между указанными широтами и долготами.Вы можете получить их, получив границы вашей карты и извлекая юго-запад и северо-восток широта / долгота.
export default {
data() {
return {
bounds: {},
map: {},
mapName: "map",
estates: [],
markers: [] // Added markers array here
}
},
mounted() {
this.initMap(); // On "mounted" only call initMap
},
methods: {
initMap: function() {
//giving specific location of japan.
this.bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(34.652500, 135.506302),
);
var mapOptions = {
mapTypeId: 'roadmap',
center: new google.maps.LatLng(0, 0),
zoom: 5
};
this.map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
let self = this;
var boundsListener = google.maps.event.addListener((this.map), 'idle', function(event) {
self.getMarkers(); // When map is idle, get markers
});
this.map.fitBounds(this.bounds);
},
getMarkers: function() {
// Get current map bounds
let bounds = this.map.getBounds();
let southWest = bounds.getSouthWest();
let northEast = bounds.getNorthEast();
// Send request with min/max latitude and longitude to only fetch markers for that area
axios.get('/ajax', {
params: {
fromLat: southWest.lat(),
toLat: northEast.lat(),
fromLng: southWest.lng(),
toLng: northEast.lng(),
}
}).then((response) => {
this.estates = response.data;
this.updateMarkers();
});
},
updateMarkers: function() {
// Remove previous markers
for (let i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
// Reset markers array
this.markers = [];
// Add current markers
for (i = 0; i < estates.length; i++) {
var position = new google.maps.LatLng(estates[i].lat, estates[i].lng);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: '/img/marker.png',
url: "/pages/" + estates[i].id,
});
// Push marker to markers array for future removal
this.markers.push(marker);
}
}
}
}
В вашем контроллере вам нужно получить параметры, которые вы отправляете с запросом axios (fromLat
, toLat
и т. д.)
public function ajax() {
// Here you need to retrieve the parameters sent by the axios request !
// And set them as $fromLat, $toLat, etc.
$data = \DB::table('allestates')
->where('lat', '>', $fromLat)
->where('lat', '<', $toLat)
->where('lng', '>', $fromLng)
->where('lng', '<', $toLng)
->get();
$response = response()->json($data);
return $response;
}
Не проверено, но это должно работать.Вам нужно адаптировать некоторые части!Читайте также мои комментарии в коде.
Примечание: Событие bounds_changed
запускается несколько раз, когда пользователь перетаскивает карту, поэтому таким образом вы собираетесь отправить много запросов.в вашу базу данных.Вместо этого вам, вероятно, следует предпочесть другое событие, такое как idle
, или как-то отложить запуск вашего вызова ajax, чтобы уменьшить количество запросов.