【问题标题】:Put a GeoJSON on a Leaflet map: Invalid GeoJSON object. throw new Error('Invalid GeoJSON object.');将 GeoJSON 放在 Leaflet 地图上:无效的 GeoJSON 对象。 throw new Error('无效的 GeoJSON 对象。');
【发布时间】:2014-10-02 16:20:49
【问题描述】:

我在构建 GeoJSON 并将其放在地图上的传单代码方面遇到了一些问题。

GeoJSON 是根据服务的 XML 响应构建的。

错误是

无效的 GeoJSON 对象。 throw new Error('无效的 GeoJSON 对象。');

我的代码是……

<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>

您可以复制/粘贴它并在您的台式机/笔记本电脑上工作。

请注意,如果您取消注释该行 ....

//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 中运行。

欢迎提出任何建议!

提前谢谢你!!

切萨雷

【问题讨论】:

  • 您的 JSON 无效,因为它末尾有一个额外的逗号。 jsonlint.com 是你的朋友。错误消息中有一条线索:D
  • 谢谢约翰!我对此不太确定(但我尝试......)。如果我复制警报消息中显示的构建的 GeoJSON 并将其“按原样”放在变量中(因此使用额外的逗号 ...),它可以正常工作......所以......这是我的疑问! :-)
  • 准备。 IE 对 Javascript 中的额外逗号之类的东西也更加挑剔。但是,无论如何,从有效的 (Geo)JSON 开始总是一个好主意。
  • 我试过了......我的 GeoJSON 现在是 {"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]}}]} 和 jsonlint.com验证它,但我的代码不起作用...
  • 控制台有错误吗?

标签: leaflet geojson


【解决方案1】:

问题在于我试图将字符串用作 JSON 对象。

解决方案是使用 jQuery.parseJSON 函数将我的 JSON 代码 (addressPCN1) 字符串转换为 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>

【讨论】:

    【解决方案2】:

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

    然后用JSON.parse()解析你的文本格式的数据:

    L.geoJSON(JSON.parse(data)).addTo(this.map);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多