Adicionando pop-up à camada GeoJSON no Leaflet


8

Eu sou novo no trabalho com a API do Leaflet e estou com problemas para criar pop-ups para uma camada GeoJSON. Eu olhei para o seguinte post como uma referência e ainda estou tendo dificuldades: vincular matrizes aninhadas como geojson pop-ups no folheto

Meus dados do GeoJson se parecem com:

{
    "type": "FeatureCollection",
    "features": [
        {
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -73.97364044189453,
                    40.66893768310547
                ]
            },
            "type": "Feature",
            "properties": {
                "lon": -73.97364044189453,
                "lat": 40.66893768310547,
                "version": "1.1",
                "t": 1381167616,
                "device": "iPhone3,3",
                "alt": 67,
                "os": "6.1.3"
            }
        },
        {
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -73.96121215820312,
                    40.66240692138672
                ]
            },
            "type": "Feature",
            "properties": {
                "lon": -73.96121215820312,
                "lat": 40.66240692138672,
                "version": "1.1",
                "t": 1381171200,
                "device": "iPhone3,3",
                "alt": 45,
                "os": "6.1.3"
            }
        }

    ]
}

Meu folheto js é o seguinte:

// create a variable to load Stamen 'toner' tiles
var layer = new L.StamenTileLayer("toner");

// initialize and set map center and zoom
var map = L.map('map', {
    center: new L.LatLng(40.67, -73.94),
    zoom: 12
});

// create the map 
map.addLayer(layer);

// on each feature use feature data to create a pop-up
function onEachFeature(feature, layer) {

    if (feature.properties) {

        var popupContent;
        popupContent = feature.properties.t;

        console.log(popupContent);    
    }
    layer.bindPopup(popupContent);
}

// grab the processed GeoJSON through ajax call
var geojsonFeature = (function() {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'url': "/data/test_random.json",
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });
        return json;
    })();

// create an object to store marker style properties
var geojsonMarkerOptions = {
    radius: 10,
    fillColor: "rgb(255,0,195)",
    color: "#000",
    weight: 0,
    opacity: 1,
    fillOpacity: 1
};

// load the geojson to the map with marker styling
L.geoJson(geojsonFeature, {

    style: function (feature) {
        return feature.properties && feature.properties.style;
    },

    onEachFeature: onEachFeature,

    pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, geojsonMarkerOptions)
    }
}).addTo(map);

A console.log(popupContent);chamada dentro da onEachFeaturefunção está retornando dados, no entanto, quando clico nos pontos GeoJSON no mapa, recebo o seguinte erro: Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist.

Eu tentei investigar isso sem sucesso até agora.

Respostas:


8

Aqui está um exemplo que eu tenho do carregamento de geojson a partir de um serviço WFS: http://maps.gcc.tas.gov.au/dogexerciseareas.html

Este é outro exemplo de carregamento do topojson (semelhante, mas diferente): http://agl.pw/examples/NRM_Regions/map.html

Aqui está um código simples que eu uso para carregar uma camada:

var myLayer = L.geoJson().addTo(map);
$.getJSON("data/buildings.json", function(json) {
  myLayer.addData(json);
});

Então você pode fazer interatividade e estilo com algo assim:

    success : function (response) {
        DogExerciseAreas = L.geoJson(response, {
            style: function (feature) {
                return {
                    stroke: false,
                    fillColor: 'FFFFFF',
                    fillOpacity: 0
                };
            },
            onEachFeature: function (feature, layer) {
                popupOptions = {maxWidth: 200};
                layer.bindPopup("<b>Site name:</b> " + feature.properties.sitename +
                    "<br><b>Dog Exercise: </b>" + feature.properties.dog_exercise +
                    "<br><br>Please ensure that tidy up after your dog. Dogs must be kept under effective control at all times."
                    ,popupOptions);
            }
        }).addTo(map);
    }

EDIT: um exemplo do site do folheto sobre pontos de estilo (a partir daqui http://leafletjs.com/examples/geojson.html ):

var geojsonMarkerOptions = {
    radius: 8,
    fillColor: "#ff7800",
    color: "#000",
    weight: 1,
    opacity: 1,
    fillOpacity: 0.8
};

L.geoJson(someGeojsonFeature, {
    pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, geojsonMarkerOptions);
    }
}).addTo(map);

EDIT2: adicionada uma solução para esse problema. Veja aqui: https://gist.github.com/alexgleith/7112515

Tudo o que você precisa fazer agora é editar o bit em que diz 'popupContent' para adicionar seu bit e alterar o código para carregar dados do arquivo.


graças alexgleith, isso parece funcionar e olhar para seus exemplos também é útil. Porém, como eu adicionaria a função pointToLayer que exibe dados de pontos como marcadores de círculo?
— clhenrick

Boa pergunta, adicionei um pouco ao final da minha postagem. Eu acho que você pode basicamente fazer isso com um estilo para os pontos que são criados.
— Alex Leith

para que os marcadores de estilo padrão tenham pop-ups funcionais, mas não marcadores de círculo. Por alguma razão, quando eu as reuni, parece que não funciona: pastebin.com/T9E9XpQM Se você remover as linhas 68-70, os pop-ups funcionarão. a partir de agora a função pointToLayer não altera o estilo do ponto. Eu o tenho no lugar errado no meu código?
— clhenrick

Tente adicionar este: .bindPopup ("<b> Time: </b>" + time + "<br> <b> Altitude: </b>" + feature.properties.alt + "meters", popupOptions); até o final da linha 69 Você está fazendo tudo duas vezes, eu acho!
— Alex Leith

1
Adicionado uma essência com a solução. Talvez você possa tentar manter seu código bonito e arrumado no futuro! Você tinha pedaços por toda parte! Entre em contato se tiver algum problema para que meu código funcione. Você pode vê-lo aqui: rawgithub.com/alexgleith/7112515/raw/…
— Alex Leith
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.