jQuery 谷歌地图 - 来自 extern json 的多个标记

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15144691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:27:33  来源:igfitidea点击:

Google Maps - Multiple marker from extern json

javascriptjqueryajaxjson

提问by Maxi

I have to add multiple marker to a google map, but the data is in an extern json file.

我必须向谷歌地图添加多个标记,但数据位于外部 json 文件中。

At the moment Im running it like this

目前我像这样运行它

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
  });
} 

Now im trying to exlude the Json File to an another file, but sadyl I cant get it to work ;(

现在我试图将 Json 文件排除在另一个文件中,但萨德尔我无法让它工作;(

Code

代码

$.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

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)."
  }

Thanks for your help

谢谢你的帮助

回答by halex

There are two problems in your code. Your json file misses the [at the beginning and ]at the end. Your javascript is wrong too, you want to do something with the json in the callback of getJSON. The code for your problem is:

您的代码中有两个问题。您的 json 文件[在开头和]结尾都错过了。你的javascript也错了,你想在.js的回调中对json做一些事情getJSON。您的问题的代码是:

$.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
        });
    });
});


EDIT:

编辑:

Here is a working example based on the google maps tutorial. You need the correct file foo.txt:

这是一个基于谷歌地图教程的工作示例。您需要正确的文件foo.txt

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=true">
    </script>
    <script type="text/javascript">
      var map;
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(58, 16),
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
      }
    </script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>    
  </head>
  <body onload="initialize()">
    <div id="map_canvas" style="width:100%; height:100%"></div>
    <script type="text/javascript">
      $(document).ready(function() {
        $.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,
                title: data.title
            });
            marker.setMap(map);
          });
        });
      });
    </script>
  </body>
</html>

回答by mattsnow

The example halex provided didn't work for me. I sorted it out by adding square brackets into foo.txtto declare it as an array and running a web server to access the html file, rather than just opening it in a browser.

提供的示例 halex 对我不起作用。我通过添加方括号将foo.txt其声明为数组并运行 Web 服务器来访问 html 文件来整理它,而不是仅仅在浏览器中打开它。

I also needed to add a delay:

我还需要添加一个延迟:

setTimeout(function (){marker.setMap(map);}, 1000); 

Now it works beautifully!

现在它运行得很漂亮!

回答by rafa226

In the Google maps documentation you can find an example : https://developers.google.com/maps/documentation/javascript/importing_data

在 Google 地图文档中,您可以找到一个示例:https: //developers.google.com/maps/documentation/javascript/importing_data

JQuery not needed

不需要 JQuery

<div id="map"></div>
<script>
  var map;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: new google.maps.LatLng(2.8,-187.3),
      mapTypeId: 'terrain'
    });

    // Create a <script> tag and set the USGS URL as the source.
    var script = document.createElement('script');
    // This example uses a local copy of the GeoJSON stored at
    // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
    script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  // Loop through the results array and place a marker for each
  // set of coordinates.
  window.eqfeed_callback = function(results) {
    for (var i = 0; i < results.features.length; i++) {
      var coords = results.features[i].geometry.coordinates;
      var latLng = new google.maps.LatLng(coords[1],coords[0]);
      var marker = new google.maps.Marker({
        position: latLng,
        map: map
      });
    }
  }
</script>