Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created December 27, 2019 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/bee2db1f99ad76d959eb5117a423ac91 to your computer and use it in GitHub Desktop.
Save parzibyte/bee2db1f99ad76d959eb5117a423ac91 to your computer and use it in GitHub Desktop.
let ultimaCapa; // Para removerla cada vez que se selecciona otra categoría
const LATITUD_CENTRO = 19.413793,
LONGITUD_CENTRO = -99.128145,
ZOOM = 15;
const mapa = new ol.Map({
target: 'mapa', // el id del elemento en donde se monta
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([LONGITUD_CENTRO, LATITUD_CENTRO]),
zoom: ZOOM,
})
});
const refrescarMapaConCategoria = categoria => {
fetch(`coordenadas.php?categoria=${categoria}`)
.then(datos => datos.json())
.then(coordenadasConIcono => {
dibujarMarcadoresEnMapa(coordenadasConIcono);
});
};
const dibujarMarcadoresEnMapa = coordenadasConIcono => {
if (ultimaCapa) {
mapa.removeLayer(ultimaCapa);
}
const { icono, coordenadas } = coordenadasConIcono;
const marcadores = [];
coordenadas.forEach(coordenada => {
let marcador = new ol.Feature({
geometry: new ol.geom.Point(
ol.proj.fromLonLat([coordenada.longitud, coordenada.latitud])
),
});
marcador.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
src: icono,
}))
}));
marcadores.push(marcador);
});
ultimaCapa = new ol.layer.Vector({
source: new ol.source.Vector({
features: marcadores,
}),
});
mapa.addLayer(ultimaCapa);
};
const $select = document.querySelector("#selectCategorias");
const obtenerCategoriaSeleccionada = () => $select.options[$select.selectedIndex].value;
const refrescarMapaConCategoriaSeleccionada = () => refrescarMapaConCategoria(obtenerCategoriaSeleccionada())
// Cuando seleccionen otra opción, refrescar el mapa
$select.addEventListener("change", refrescarMapaConCategoriaSeleccionada);
// Algunos eventos que podrían ser de utilidad
mapa.on('singleclick', function(evt) {
var feature = mapa.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
// Aquí se puede filtrar la feature
return feature;
});
if (feature) {
console.log("Click en: ", feature);
}
});
let zoomActual = mapa.getView().getZoom();
mapa.on('moveend', function(e) {
let nuevoZoom = mapa.getView().getZoom();
if (zoomActual != nuevoZoom) {
console.log('Nuevo zoom: ' + nuevoZoom);
zoomActual = nuevoZoom;
}
});
// Al inicio de todo, obtener con la primer categoría
refrescarMapaConCategoriaSeleccionada();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment