在Leaflet地图上放一个GeoJSON。Invalid GeoJSON object. throw new Error('Invalid GeoJSON object.');

问题描述 投票:3回答:2

我的Leaflet代码遇到了一些麻烦,它建立了一个GeoJSON并将其放在地图上。

GeoJSON是由一个服务的XML响应建立的。

错误是

Invalid GeoJSON object. throw new Error('Invalid GeoJSON object.');

我的代码是...

<html>
<head>
<title>Prova caricamento WMS Indirizzi del PCN</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css"/>
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>   
    <script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet-src.js"></script>

<script>

    var browser = navigator.userAgent.toLowerCase();
    var isIE = (browser.indexOf("msie")>-1 || browser.indexOf("trident")>-1);


    if (isIE && window.XDomainRequest) {
                    if (window.XDomainRequest) {
                        var query = 'http://wms.pcn.minambiente.it/ogc?map=/ms_ogc/wfs/Numeri_Civici_2012.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=IN.NUMERICIVICI.2012&SRSNAME=EPSG:4326&bbox=7.719,44.849,7.72,44.85&outputFormat=GML2';
                        var xdr = new XDomainRequest();
                        if (xdr) {
                            xdr.onload = function () {
                                addressPCN(data);                               
                            }
                            xdr.onerror = function () { 
                                alert("KO");
                            }
                            xdr.open('GET', query);
                            xdr.send();
                        }
                    }
                }
                else {
                    var query = 'http://wms.pcn.minambiente.it/ogc?map=/ms_ogc/wfs/Numeri_Civici_2012.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=IN.NUMERICIVICI.2012&SRSNAME=EPSG:4326&bbox=7.719,44.849,7.72,44.85&outputFormat=GML2';
                    $.ajax({
                        type: "GET",
                        url: query,
                        dataType: "text",
                        crossDomain: true,
                        success: function (data) {
                                       addressPCN(data);                                
                        },
                        error: function (response, textStatus, errorThrown) {
                            alert("KO");
                            alert(errorThrown);
                        }
                    });
                }   


    var map = L.map('map').setView([42, 12], 5);

    L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="http://mapbox.com">Mapbox</a>',
        id: 'examples.map-20v6611k'
    }).addTo(map);

            function addressPCN (addressList) {

             //alert("In function addressList");
             //alert(addressList);

                     var addressPCN = '{"type": "FeatureCollection","features":[';
                     $xmlData = $.parseXML(addressList);
                     $features = $('gml\\:featureMember, featureMember', $xmlData);
                     //alert($features.length);
                     $features.each(function () {
                               var $this = $(this);
                               //alert($this.find('ms\\:nome, nome').text() + ' - ' + $this.find('ms\\:civico, civico').text());
                               addressPCN = addressPCN + '{"type": "Feature", "properties": { "popupContent": "' + $this.find('ms\\:nome, nome').text() + ' ' + $this.find('ms\\:civico, civico').text() + '", ' + '"show_on_map": true }, "geometry": { "type": "Point", "coordinates": [' + $this.find('gml\\:Point, Point').find('gml\\:coordinates, coordinates').text() + ']}},'
                     });                         
                     var addressPCN = addressPCN + ']}';

                     alert(addressPCN);

             function onEachFeature(feature, layer) {
                      if (feature.properties && feature.properties.popupContent) {
                         layer.bindPopup(feature.properties.popupContent);
                      }
                     }


                     //var addressPCN = {"type": "FeatureCollection","features":[{"type": "Feature", "properties": { "popupContent": "Via Pegolo 9", "show_on_map": true }, "geometry": { "type": "Point", "coordinates": [7.719490,44.849197]}},{"type": "Feature", "properties": { "popupContent": "Via Pegolo 8", "show_on_map": true }, "geometry": { "type": "Point", "coordinates": [7.719490,44.849197]}},]};
             L.geoJson(addressPCN, {
                   onEachFeature: onEachFeature
             }).addTo(map);
            }

</script>

你可以把它复制粘贴到你的台式机上。

请注意,如果你取消了这一行的comment......。

//var addressPCN = {"type": "FeatureCollection","features":[{"type": "Feature", "properties": { "popupContent": "Via Pegolo 9", "show_on_map": true }, "geometry": { "type": "Point", "coordinates": [7.719490,44.849197]}},{"type": "Feature", "properties": { "popupContent": "Via Pegolo 8", "show_on_map": true }, "geometry": { "type": "Point", "coordinates": [7.719490,44.849197]}},]};

........你已经得到了我正在构建的GeoJSON(你可以将它与警报信息......匹配)。

在这种情况下,所有的工作都是正确的。

注意:你必须使用Firefox或Chrome浏览器的时刻,我的代码仍然不能工作在IE。

任何建议都很感激!

先谢谢你!

Cesare

leaflet geojson
2个回答
6
投票

问题是关于我试图使用一个字符串作为JSON对象。

解决方案是使用 jQuery.parseJSON 我的字符串与我的JSON代码(地址PCN1)转换为Javascript JSON对象的函数。

这里你的代码,工作...

<!DOCTYPE html>
<html>
 <head>
  <title>Prova caricamento WMS Indirizzi del PCN</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css"/>
 </head>
 <body>
  <div id="map" style="width: 600px; height: 400px"></div>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>   
  <script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet-src.js"></script>

  <script>

    var browser = navigator.userAgent.toLowerCase();
    var isIE = (browser.indexOf("msie")>-1 || browser.indexOf("trident")>-1);


    if (isIE && window.XDomainRequest) {
                    if (window.XDomainRequest) {
                        var query = 'service_url';
                        var xdr = new XDomainRequest();
                        if (xdr) {
                            xdr.onload = function () {
                          addressPCN(xdr.responseText);                             
                            }
                            xdr.onerror = function () { 
                                alert("KO");
                            }
                            xdr.open('GET', query);
                            xdr.send();
                        }
                    }
                }
                else {
                    var query = 'service_url';
                    $.ajax({
                        type: "GET",
                        url: query,
                        dataType: "text",
                        crossDomain: true,
                        success: function (data) {
                                    //alert("OK");
                                    //alert(data);
                                    addressPCN(data);                               
                                    alert($this.find('ms\\:nome, nome').text() + ' - ' + $this.find('ms\\:civico, civico').text());
                        },
                        error: function (response, textStatus, errorThrown) {
                            alert("KO");
                            alert(errorThrown);
                        }
                    });
                }   


    var map = L.map('map').setView([42, 12], 5);

    L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="http://mapbox.com">Mapbox</a>',
        id: 'examples.map-20v6611k'
    }).addTo(map);

            function addressPCN (addressList) {

                     var addressPCN = '{"type": "FeatureCollection","features":[';
                     $xmlData = $.parseXML(addressList);
                     $features = $('gml\\:featureMember, featureMember', $xmlData);
                     $features.each(function () {
                               var $this = $(this);
                               //alert($this.find('ms\\:nome, nome').text() + ' - ' + $this.find('ms\\:civico, civico').text());
                               addressPCN = addressPCN + '{"type": "Feature", "properties": { "popupContent": "' + $this.find('ms\\:nome, nome').text() + ' ' + $this.find('ms\\:civico, civico').text() + '", ' + '"show_on_map": true }, "geometry": { "type": "Point", "coordinates": [' + $this.find('gml\\:Point, Point').find('gml\\:coordinates, coordinates').text() + ']}},'
                     });                         
                     var addressPCN = addressPCN + ']}';

                     alert(addressPCN);

                     var addressPCN1 = addressPCN.replace(',]}',']}');

                     alert(addressPCN1);

                     var addressPCN2 = jQuery.parseJSON(addressPCN1);

                     alert(addressPCN2);

             function onEachFeature(feature, layer) {
                      if (feature.properties && feature.properties.popupContent) {
                         layer.bindPopup(feature.properties.popupContent);
                      }
                     }

             L.geoJson(addressPCN2, {
                   onEachFeature: onEachFeature
             }).addTo(map);
            }

  </script>
 </body>
</html>

0
投票

首先,确保Geo JSON数据是有效的数据与 http:/geojsonlint.com 或任何其他服务。如果有错误,请修复。

然后用以下方法解析您的文本格式的数据 JSON.parse():

L.geoJSON(JSON.parse(data)).addTo(this.map);
© www.soinside.com 2019 - 2024. All rights reserved.