如何从json文件加载多个标记?

时间:2015-09-07 07:11:43

标签: javascript jquery json google-maps google-maps-api-3

我正在开发一个jquery移动地图应用程序,我有map.html,map.js和map.json文件,如下所示

function initialize() {
        var latitude = 57.95,
            longitude = 14.65,
            radius = 8000, //how is this set up
            center = new google.maps.LatLng(latitude,longitude),
            bounds = new google.maps.Circle({center: center, radius: radius}).getBounds(),
            mapOptions = {
                center: center,
                zoom: 9,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
            };

        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

        setMarkers(center, radius, map);
    }

    function setMarkers(center, radius, map) {
        var json = (function () { 
            var json = null; 
            $.ajax({ 
                'async': false, 
                'global': false, 
                'url': "./map.json", 
                'dataType': "json", 
                'success': function (data) {
                     json = data; 
                 }
            });
            return json;
        })();

        var circle = new google.maps.Circle({
                strokeColor: '#000000',
                strokeOpacity: 0.25,
                strokeWeight: 1.0,
                fillColor: '#ffffff',
                fillOpacity: 0.1,
                clickable: false,
                map: map,
                center: center,
                radius: radius
            });
        var bounds = circle.getBounds();

        //loop between each of the json elements
        for (var i = 0, length = json.length; i < length; i++) {
            var data = json[i],
            latLng = new google.maps.LatLng(data.lat, data.lng); 



            if(bounds.contains(latLng)) {
                // Creating a marker and putting it on the map
                var marker = new google.maps.Marker({
                    position: latLng,
                    map: map,
                    title: data.content
                });
                infoBox(map, marker, data);
            }
        }

        circle.bindTo('center', marker, 'position');
    }

    function infoBox(map, marker, data) {
        var infoWindow = new google.maps.InfoWindow();
        // Attaching a click event to the current marker
        google.maps.event.addListener(marker, "click", function(e) {
            infoWindow.setContent(data.content);
            infoWindow.open(map, marker);
        });

        // Creating a closure to retain the correct data 
        // Note how I pass the current data in the loop into the closure (marker, data)
        (function(marker, data) {
          // Attaching a click event to the current marker
          google.maps.event.addListener(marker, "click", function(e) {
            infoWindow.setContent(data.content);
            infoWindow.open(map, marker);
          });
        })(marker, data);
    }

   google.maps.event.addDomListener(window, 'load', initialize);
[{ 
    "lat": 57.95, 
    "lng": 14.65, 
    "content":"test content1" 
}, 
{ 
    "lat": 57.9, 
    "lng": 14.6, 
    "content":"test content2" 
}, 
{ 
    "lat": 57.85, 
    "lng": 14.55,
    "content":"test content3"
}]
<!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.google.com/maps/api/js?sensor=false"></script>
     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
     <script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
    </script>
    <script src="./map.js"></script>
  </head>
  <body>
    <div id="map-canvas"/>
  </body>
</html>

但是在我的代码中没有看到标记....当我尝试运行单个html文件而没有任何外部.js和.json文件时它工作但是使用此代码我无法运行..

我需要知道哪里出错了,还需要帮助: 1.在地图中显示多个标记 2.点击标记时,它应在内容标记中显示消息

等待帮助......提前谢谢......

4 个答案:

答案 0 :(得分:1)

该示例没有任何问题,因为您尝试直接从浏览器打开html页面(因此通过文件协议加载map.json),很可能是您收到此错误的原因。

基本上有两种选择:

选项1

您可以在localhost上安装网络服务器并访问您的网页,也可以在网络上的某处上传map.json并将网址更改为http://example.com/map.json

选项2

允许浏览器访问本地文件,例如在Chrome中,您可以指定allow-file-access-from-files标记,例如:

> .\chrome.exe --allow-file-access-from-files

答案 1 :(得分:0)

请查看此解决方案的代码,

jQuery(function($) {
// Asynchronously Load the map API 
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);});

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };



// Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);

// Multiple Markers
var markers = [
    ['London Eye, London', 51.503454,-0.119562],
    ['Palace of Westminster, London', 51.499633,-0.124755]
];

// Info Window Content
var infoWindowContent = [
    ['<div class="info_content">' +
    '<h3>London Eye</h3>' +
    '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' +        '</div>'],
    ['<div class="info_content">' +
    '<h3>Palace of Westminster</h3>' +
    '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
    '</div>']
];

// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map  
for( i = 0; i < markers.length; i++ ) {
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
        position: position,
        map: map,
        title: markers[i][0]
    });

    // Allow each marker to have an info window    
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            infoWindow.open(map, marker);
        }
    })(marker, i));

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
    this.setZoom(14);
    google.maps.event.removeListener(boundsListener);
});

}

参考链接:http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/

答案 2 :(得分:0)

我发现DataLayer GeoJSON 功能块是在地图上绘制静态点或区域的更简单方法。我建议用GeoJSON&amp;更换你的数据文件。使用 map.data.loadGeoJson(url)调用。

DataLayer链接还说明了如何加载网址。它谈到了CORS和你的问题。

答案 3 :(得分:0)

这个问题已经回答了, 在cmd中运行它以通过让它访问本地文件来启动chrome。

&#34; C:\ Program Files(x86)\ Google \ Chrome \ Application \ chrome.exe&#34; --allow-file-access-from-files

休息一切正确,我可以显示多个标记,然后点击一个信息窗口就会打开..

为了更具可读性,您可以更改latlang初始化和半径。在上面的代码片段中,只有2个标记可见,尽管json文件中有3个。增加半径以查看第3个标记 感谢所有人的帮助