Qual é a maneira correta no OpenLayers (OSM) de acionar um pop-up para um recurso?
-
14-11-2019 - |
Pergunta
Eu tenho o ID do recurso, posso pegar a camada do marcador no loadend GeoRSS, mas ainda não tenho certeza de como fazer com que o pop-up apareça programaticamente.
Criarei o pop-up sob demanda, se for necessário, mas parece que devo conseguir o ID do marcador desenhado no mapa e chamar algum evento nele.Eu tentei usar jQuery e chamar o $(marker-id).click()
evento nos elementos do mapa, mas isso não parece estar funcionando.o que estou perdendo?
Como me pediram o código e presumi que fosse clichê, aqui está onde estou até agora:
map = new OpenLayers.Map('myMap');
map.addLayer(new OpenLayers.Layer.OSM());
map.addLayer(new OpenLayers.Layer.GeoRSS(name,url));
//I've done some stuff as well in re: projections and centering and
//setting extents, but those really don't pertain to this question.
Em outro lugar, fiz alguns modelos de jQuery e criei uma boa lista de todos os pontos que estão sendo mostrados no mapa.Eu sei como fazer um retorno de chamada da camada loadend
e obter o objeto de camada, sei como recuperar minha camada do mapa manualmente, sei como percorrer a coleção de camadas e encontrar minha camada.Então posso pegar qualquer um desses detalhes sobre o pop-up, mas ainda não sei como usar os métodos internos do DOM ou desta API para torná-lo tão fácil quanto element.click()
que é o que eu preferiria fazer.
Solução
Você não precisa clicar no recurso para abrir um pop-up.
Primeiro você precisa de uma referência ao recurso a partir do ID do recurso.eu faria isso no loadend
evento da camada GeoRSS, usando o markers
propriedade na camada.
Supondo que você tenha uma referência ao seu recurso, eu escreveria um método que lida com o pop-up automático:
var popups = {}; // to be able to handle them later
function addPopup(feature) {
var text = getHtmlContent(feature); // handle the content in a separate function.
var popupId = evt.xy.x + "," + evt.xy.y;
var popup = popups[popupId];
if (!popup || !popup.map) {
popup = new OpenLayers.Popup.Anchored(
popupId,
feature.lonlat,
null,
" ",
null,
true,
function(evt) {
delete popups[this.id];
this.hide();
OpenLayers.Event.stop(evt);
}
);
popup.autoSize = true;
popup.useInlineStyles = false;
popups[popupId] = popup;
feature.layer.map.addPopup(popup, true);
}
popup.setContentHTML(popup.contentHTML + text);
popup.show();
}
Outras dicas
finalmente voltei a isso e fiz algo completamente diferente, mas a resposta dele foi boa.
//I have a list of boxes that contain the information on the map (think google maps)
$('.paginatedItem').live('mouseenter', onFeatureSelected).live('mouseleave',onFeatureUnselected);
function onFeatureSelected(event) {
// I stuff the lookup attribute (I'm lazy) into a global
// a global, because there can be only one
hoveredItem = $(this).attr('lookup');
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
}
function onFeatureUnselected(event) {
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
/* Do something here to stop the indication of the onhover */
hoveredItem = null;
}
function findFeatureById(featureId) {
for (var key in map.layers) {
var layer = map.layers[key];
if (layer.hasOwnProperty('features')) {
for (var key1 in layer.features) {
var feature = layer.features[key1];
if (feature.hasOwnProperty('id') && feature.id == featureId) {
return feature;
}
}
}
}
return null;
}
observe também que eu mantenho map
como global, então não preciso readquiri-lo toda vez que quiser usá-lo