리플렛 맵에 외부 GeoJSON 파일을로드 하시겠습니까?


53

geoJSON (폴리곤) 파일을 전단지지도에로드하고 싶습니다. geoJSON이 자바 스크립트 코드에 포함 된 예제를 보았지만 외부 파일로 어떻게 수행되는지 보여주는 예제를 찾을 수 없습니다.

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" />
    <script src="usStates.geojson" type="text/javascript"></script>
    <style>
        html, body, #map {
            height: 100%;
        }
        body {
            padding: 0;
            margin: 0;
        }
    </style>
</head>

<body>
    <div id="map" style="height: 100%"</div>
    <script src="http://d3js.org/d3.v2.min.js?2.9.3"></script>
    <script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>

    <script type="text/javascript"> 

    var map = L.map('map').setView([38.57, -94.71], 4);

    L.tileLayer('http://{s}.tile.cloudmade.com/9067860284bc491e92d2342cc51d47d9/998/256/{z}/{x}/{y}.png', {attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> Imagery © <a href="http://cloudmade.com">CloudMade</a>'}).addTo(map);

    var featureStyle = {
        "color": "#ff7800",
        "weight": 5, 
        "opacity": 0.2
    };

    L.geoJson(usStates).addTo(map);

    </script>

</body>

geojson을 geojson.io로
— Mapperz

@Mapperz OP는 geojson 내용의 내용을 스크립트에 붙여 넣는 방법에 대해 묻지 않았습니다.
— Dave-Evans

답변:


35

Leaflet-Ajax를 살펴보십시오. 모든 것을 합리화합니다. Neogeomat에 대해 언급하여 찬성 투표합니다.

스크립트를 가져옵니다 여기 ( GitHub의 REPO )와 헤더에 추가 :

<script src="/js/leaflet-0.7.2/leaflet.ajax.min.js"></script>

그런 다음 파일 이름으로 업로드해야합니다.

var geojsonLayer = new L.GeoJSON.AJAX("foo.geojson");       
geojsonLayer.addTo(map);

정말 직접 수정하고 작동합니다. 그래


26

jquery Ajax를 사용하여 데이터를로드 한 다음 추가 할 수 있습니다.

var district_boundary = new L.geoJson();
district_boundary.addTo(map);

$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(data) {
    $(data.features).each(function(key, data) {
        district_boundary.addData(data);
    });
}
}).error(function() {});

또는 leaf-ajax 플러그인을 사용할 수 있습니다


14

여기 내 최소 바닐라 js 솔루션이 있습니다. 엄마, 파일에 대한 빠른 아약스 호출에 jquery가 필요하지 않습니다.

let xhr = new XMLHttpRequest();
xhr.open('GET', 'uk_outline.geojson');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = function() {
    if (xhr.status !== 200) return
    L.geoJSON(xhr.response).addTo(map);
};
xhr.send();

예를 들어 주셔서 감사합니다- 팩토리 함수에 new대한 키워드를 가져 geoJSON왔지만 거기에 setRequestHeader 줄에 CORS 오류가 발생하여 제거했으며 정상적으로 작동했습니다 (내 서버의 일부 설정이어야 함).
— Brian Burns

에 XML Parsing Error: not well-formed오류가 발생했습니다 Line Number 1, Column 1:. 글쎄, 데이터는 geojson이기 때문에 왜 XML로 파싱하려고합니까? 문제를 이해하지 못했지만 Ajax없이 데이터를 가져오고 싶습니다.
— Aaron Bramson

@AaronBramson 다른 시도가 있습니다. 이것은 내가했던 오래된 코드 비트였습니다. responseType을 설정하고 responseText를 구문 분석하지 않는 응답을 사용해야합니다. 코드 스 니펫을 업데이트했습니다.
— Dennis Bauszus

네, 대단합니다! 별도의 외부 패키지 없이도 데이터 파일을 편집 할 필요없이 바로 사용할 수 있습니다. 이것이 가장 좋은 대답입니다.
— Aaron Bramson

11

head 요소에서 파일을 참조하십시오.

    <link rel="stylesheet" type="text/css" href="leaflet/leaflet.css" />
    <!--[if lte IE 8]>
        <link rel="stylesheet" type="text/css" href="css/leaflet.ie.css" />
    <![endif]-->
    <script src="leaflet/leaflet.js"></script>
    <script src="hydro_s.geojson" type="text/javascript"></script>
    <script src="hydro_l.geojson" type="text/javascript"></script>
    <style>
        html, body, #map {
            height: 100%;
        }
        body {
            padding: 0;
            margin: 0;
        }
    </style>
    <title>Leaflet Map with GeoJson</title>
 </head>

그리고 몸에서 :

<body>
    <div id="map"></div>
    <script type="text/javascript">

        var map = L.map('map', {
            center: [45.57, -73.5648],
            zoom: 10
        });

         /* Hydro */
        var hydro = new L.LayerGroup();
        L.geoJson(hydro_s, {style: hydrosStyle}).addTo(hydro);
        L.geoJson(hydro_l, {style: hydrolStyle}).addTo(hydro);

    </script>
</body>

레이어 그룹에 "넣을"필요는 없습니다 ...


완전한! 이것이 내가 찾던 것입니다!
— bailey

1
파이어 폭스 내가 무엇입니까의 방화범 웹 개발자를 이용하여 "ReferenceError가 : usStates이 정의되지 않은" "(L.geoJson (usStates) .addTo (지도);"당신이 보여처럼 파일을 참조 <script src="usStates.geojson" type="text/javascript"></script>하고 추가 L.geoJson(usStates).addTo(map);. 내 코드의 맨 아래에있는 아이디어?
— bailey

그것은 src와 함께 뭔가가 있어야합니다 ... 내 문서의 머리에 (완전히 추가하려면 내 대답을 편집)
— fgcartographix

1
참조에 변수가 필요하지 않습니까? 내 파일 확장자가 .geojson 대신 .json이라는 것이 중요합니까?
— bailey

2
데이터 파일에 변수 hydro_s, hydro_l을 정의해야하므로 기술적으로도 잘못된 GeoJSON을 만들게되므로 혼란스러운 답변입니다. 자세한 내용은 다른 답변을 참조하십시오 ...
— Florian Ledermann

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.