在Google地图中访问KML标记

3
有没有办法在使用Google Maps API时从KML文件创建“侧边栏”?
我正在使用以下类似代码将标记加载到地图上:
var myMarkerLayer = new google.maps.KmlLayer('http://example.com/WestCoast.kml');

目前这个很好,但是我怎样才能获取那些数据并循环遍历这些点?

如果可能的话,我想避免使用第三方库,虽然jQuery可以。

2个回答

8

KML只是一个XML文档,因此您可以使用jQuery处理它以提取所需的数据。您可以将坐标和地名存储在本地数组中,并使用此数据进行任何目的,例如:当人们在侧边栏上点击地名时,您可以使用它导航到地图上的某个点。

以下是如何处理KML文件并基于文件中的数据实现导航的示例。请注意,我不建议对大型KML文件执行此操作,因为这会使加载时间加倍(浏览器必须加载文件以处理功能)...

<script type="text/javascript" src= "http://maps.google.com/maps/api/js?sensor=false">
</script>
<script src="../js/jquery-1.4.2.min.js">
</script>
<script>
    var map;
    var nav = [];
    $(document).ready(function(){
        //initialise a map
        init();

        $.get("kml.xml", function(data){

            html = "";

            //loop through placemarks tags
            $(data).find("Placemark").each(function(index, value){
                //get coordinates and place name
                coords = $(this).find("coordinates").text();
                place = $(this).find("name").text();
                //store as JSON
                c = coords.split(",")
                nav.push({
                    "place": place,
                    "lat": c[0],
                    "lng": c[1]
                })
                //output as a navigation
                html += "<li>" + place + "</li>";
            })
            //output as a navigation
            $(".navigation").append(html);

            //bind clicks on your navigation to scroll to a placemark

            $(".navigation li").bind("click", function(){

                panToPoint = new google.maps.LatLng(nav[$(this).index()].lng, nav[$(this).index()].lat)

                map.panTo(panToPoint);
            })

        });

        function init(){


            var latlng = new google.maps.LatLng(-43.552965, 172.47315);
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map"), myOptions);



        }


    })
</script>
<html>
    <body>
        <div id="map" style="width:600px;height: 600px;">
        </div>
        <ul class="navigation">
        </ul>
    </body>
</html>

该方法要求kml文件与地图页面存在于同一域中,因为存在跨域安全限制。而使用本机的Google Maps KmlLayer将允许加载外部kml文件。 - Sean
请注意,此方法仅解决了本地KMLLayer的缺点,该图层不提供任何选项来获取KML中的其他数据,这并不意味着它可以替代原生KMLLayer,而只是一种处理XML文档的方法。 - Michal
你好 我知道这个问题很旧了,但是在使用这种方法从kml文件中获取数据后,我注意到它会给我一个错误。 nav未定义;因此,在使用nav变量之前,您需要添加var nav = []; - João Costa

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接