Created
December 27, 2019 18:40
-
-
Save parzibyte/bee2db1f99ad76d959eb5117a423ac91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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