Google地图 – 来自extern json的多个标记
我必须在谷歌地图上添加多个标记,但数据在extern json文件中。
目前我正在运行它
var json = [ { "title": "Stockholm", "lat": 59.3, "lng": 18.1, "description": "Stockholm is the capital and the largest city of Sweden and constitutes the most populated urban area in Scandinavia with a population of 2.1 million in the metropolitan area (2010)" }, { "title": "Oslo", "lat": 59.9, "lng": 10.8, "description": "Oslo is a municipality, and the capital and most populous city of Norway with a metropolitan population of 1,442,318 (as of 2010)." }, { "title": "Copenhagen", "lat": 55.7, "lng": 12.6, "description": "Copenhagen is the capital of Denmark and its most populous city, with a metropolitan population of 1,931,467 (as of 1 January 2012)." } ]; for (var i = 0, length = json.length; i < length; i++) { var data = json[i], latLng = new google.maps.LatLng(data.lat, data.lng); // Creating a marker and putting it on the map var marker = new google.maps.Marker({ position: latLng, map: map, title: data.title }); }
现在我试图将Json文件排除到另一个文件,但是sadyl我不能让它工作;(
码
$.getJSON("foo.txt", function(json1) { }); for (var i = 0, length = json.length; i < length; i++) { var data = json[i], latLng = new google.maps.LatLng(data.lat, data.lng); // Creating a marker and putting it on the map var marker = new google.maps.Marker({ position: latLng, map: map, title: data.title }); }
foo.txt的
{ "title": "Stockholm", "lat": 59.3, "lng": 18.1, "description": "Stockholm is the capital and the largest city of Sweden and constitutes the most populated urban area in Scandinavia with a population of 2.1 million in the metropolitan area (2010)" }, { "title": "Oslo", "lat": 59.9, "lng": 10.8, "description": "Oslo is a municipality, and the capital and most populous city of Norway with a metropolitan population of 1,442,318 (as of 2010)." }, { "title": "Copenhagen", "lat": 55.7, "lng": 12.6, "description": "Copenhagen is the capital of Denmark and its most populous city, with a metropolitan population of 1,931,467 (as of 1 January 2012)." }
谢谢你的帮助
您的代码中存在两个问题。 你的json文件错过了[
在开头和]
结尾。 你的javascript也是错误的,你想在getJSON
的回调中用json做些什么。 您的问题的代码是:
$.getJSON("foo.txt", function(json1) { $.each(json1, function(key, data) { var latLng = new google.maps.LatLng(data.lat, data.lng); // Creating a marker and putting it on the map var marker = new google.maps.Marker({ position: latLng, map: map, title: data.title }); }); });
编辑:
这是一个基于谷歌地图教程的工作示例。 你需要正确的文件foo.txt
:
提供的示例halex对我不起作用。 我通过在foo.txt
添加方括号将其整理出来,将其声明为数组并运行Web服务器来访问html文件,而不是仅仅在浏览器中打开它。
我还需要添加一个延迟:
setTimeout(function (){marker.setMap(map);}, 1000);
现在它工作得很漂亮!
在Google地图文档中,您可以找到一个示例: https : //developers.google.com/maps/documentation/javascript/importing_data
不需要JQuery