2015-11-08 9 views
0

我正在使用.loadGeoJson將geojson數據加載到Google Maps API實例中。我以前用過這個,但是這次它沒有加載任何數據,我不知道爲什麼。loadGeoJson不工作

我用上面的代碼是:

var localLayer = new google.maps.Data(); 
localLayer.loadGeoJson('JSON/local.geojson'); 
localLayer.setMap(map); 

我當前的代碼看起來像:

的JavaScript:

var map; 
function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     center: { 
      lat: 39.154743, 
      lng: -77.240515 
     }, 
     zoom: 10 
    }); 
}; 
$(document).ready(function() { 
    initMap(); 
    var localLayer = new google.maps.Data(); 
    localLayer.loadGeoJson('json/Schools.geojson'); 
    localLayer.setMap(map); 
}); 

HTML:

<body> 
    <div id="page"> 
     <div id="content"> 
      <h1>Title</h1> 
      <div id="map"></div> 
     </div> 
    </div> 
</body> 

CSS:

body { 
    font-family: 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif; 
} 

#map { 
    height: 400px; 
    width: 400px; 
    margin: 0 auto; 
    border: 1px solid black; 
    box-shadow: 3px 3px 10px 3px black; 
} 

文件路徑是json/Schools.geojson

我在做什麼錯?

+2

geoJson響應也會很有趣 –

+0

您的GeoJson是否有效?它是什麼樣子的?請提供證明此問題的[最小,完整,測試和可讀示例](http://stackoverflow.com/help/mcve)。 – geocodezip

+0

[我的網頁在這裏](http://alexdingis.github.io/hispanic-location-quotient/)和[我的git hub repo在這裏](https://github.com/alexdingis/hispanic-location -quotient /樹/主)。 – adin

回答

2

顯然Schools.geojson包含無效的座標,例如:[1263179.3749040514, 541288.18736040592]。您可以利用 Data Layer API來驗證Geo JSON數據。一旦不正確緯度/經度值已經提供,Data Layer API回報爲google.maps.LatLng對象的緯度屬性90值:

添加以下行:

schoolLayer.addListener('addfeature', validateData); 

其中

function validateData(o) { 

    var validateCoordinates = function (items) { 
     var validAll = items.every(function (item) { 
      var latLngs = item.getArray(); 
      valid = latLngs.every(function (latLng) { 
       return isValidLatLng(latLng); 
      }); 
      return valid; 
     }); 
     return validAll; 
    }; 

    var f = o.feature; 
    var geometry = f.getGeometry(); 
    if (geometry.getType() == "MultiPolygon") { 
     var allCoords = geometry.getArray(); 
     allCoords.forEach(function(coords) { 
      if (!validateCoordinates(coords.getArray())) { 
       document.getElementById('output').innerHTML += 'Geo JSON contains invalid lat/lng'; 
      } 
     }); 
    } else { 
     var coords = geometry.getArray(); 
     if (!validateCoordinates(coords)) { 
      document.getElementById('output').innerHTML += 'Geo JSON contains invalid lat/lng'; 
     } 
    } 
} 



function isValidLatLng(latLng) { 
    return latLng.lat() != 90; 
} 

Here is a working example演示如何驗證Geo JSON。

+1

一讀完第一行,我就回到ArcGIS,看到我在馬里蘭州立飛機上仍然有shapefile文件。然後,我看了兩個geojson文件,看到了座標的差異。對於其他讀者,請確保您的座標系在** GCS_North_American_1983 **中,然後再轉換爲geojson。 – adin