使用JSON在谷歌地图上显示标记

Display markers on Google Map using JSON

本文关键字:显示 谷歌地图 JSON 使用      更新时间:2023-09-26

我有以下测试谷歌地图:http://dev.driz.co.uk/googlemap/

我使用Foursquare标记的设计作为一个例子来测试我的代码,到目前为止,我已经实现了一个简单的显示,显示用户在世界上的位置,并使用一个小化身,当你悬停时,它会以工具提示的形式"告诉"你这一点。

下一部分使用一些JSON数据:http://dev.driz.co.uk/googlemap/data.json

我想使用存储在数据中的坐标在地图上显示这5个帖子,并以与当前标记类似的方式显示它们。然后,用户将鼠标悬停在标记上,并能够看到工具提示,例如包含以下信息:

Cameron asked:
Is Star Wars 3d still on at the cinema?
2012-05-20 02:31:21

用户应该能够点击要带到帖子的标记。

我看过谷歌地图的开发者部分,但似乎没有找到合适的东西,也不知道如何最好地将其与我的工具提示功能和地图实现结合使用。

有人能帮忙吗?张贴一些代码示例?

感谢

按照以下步骤

  1. 使用AJAX请求提取数据并将其存储在变量中。

    • 您可以为此使用jQuery。http://api.jquery.com/jQuery.getJSON/

      $.getJSON('http://dev.driz.co.uk/googlemap/data.json', function(data){
            // loop  and add markers
      });
      
    • 或者,您可以使用纯javascript和JSON解析器。

      • http://www.degraeve.com/reference/simple-ajax-example.php
      • http://www.json.org/
  2. 循环输入数据,选择每个项目并添加到地图

    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        var markerLatlng = new google.maps.LatLng(item.Post.latitude, item.Post.longitude);
        var marker = new google.maps.Marker({
            position: markerLatlng
        });
        marker.item = item; // store information of each item in marker
        marker.setMap(map); // where `map` is the instance of Google Map
        google.maps.event.addListener(marker, "click", function(mark) {
            // retrieve information using `this.item` and create dynamic HTML to show it. 
            // this.item.Post.datetime, this.item.Post.content etc.
        });
    }