访问Google地图中的KML标记
问题描述:
使用Google Maps API时,是否有任何方法可以通过KML文件创建“边栏”?访问Google地图中的KML标记
我使用这样的装载地图上的标记:
var myMarkerLayer = new google.maps.KmlLayer('http://example.com/WestCoast.kml');
这个伟大的工程,到目前为止,但我怎么能抢,通过这些点的数据和循环?
我想避免使用第三方库,如果可能的话 - 虽然jQuery是好的。
答
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>
答
这是不可能的。检查文档: http://code.google.com/apis/maps/documentation/javascript/overlays.html#KMLLayers
在“KML特征数据”:
由于KML可包括大量的功能,您可能无法按KmlLayer对象直接访问特征数据。相反,当功能显示时,它们呈现为可点击的Maps API叠加层。
由于跨域安全限制,此方法将要求kml文件与地图页面存在于相同的域中。而使用本地谷歌地图KmlLayer将允许外部kmls加载。 – Sean 2012-09-03 02:31:35
请注意,此方法简单地解决了原生KMLLayer的缺点,它不会给您任何选项来从KML获取更多数据,但这并不是要取代它,只是一种处理XML文档的方法。 – Michal 2012-09-03 20:44:32
你好 我知道这个问题很旧,但使用这种方法从kml文件中提取数据后,我发现它给了我一个错误。 nav未定义; 所以你需要添加var nav = [];在使用nav变量之前。 – JonnyDevv 2014-03-03 12:10:36