使用json文件将多个标记添加到Google地图

时间:2018-04-29 17:20:37

标签: javascript json google-maps

我有一张地图和一个包含餐馆信息的JSON文件。我需要在JSON文件中为20个餐厅添加标记到地图,但是我无法通过标记加载地图。我不认为我正确地从JSON文件中检索数据。我们将非常感谢正确方向上的一点。

这是我的代码:

  var map;
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(55.9753905, -1.6236163),
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

       map = new 
         google.maps.Map(document.getElementById("EstablishmentCollection"),
           mapOptions);
           $.getJSON("'FHRS_json.json'", 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.BusinessName
               });
               marker.setMap(map);
               });
            });

然后这是JSON文件启动的示例。有大量的餐馆,所以我不会发布所有。

 {
   "FHRSEstablishment": {
   "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
   "Header": {
   "ExtractDate": "2018-02-03",
   "ItemCount": "2369",
   "ReturnCode": "Success"
  },
"EstablishmentCollection": {
      "EstablishmentDetail": [
        {
          "FHRSID": "1011573",
          "LocalAuthorityBusinessID": "17/00395/MIXED",
          "BusinessName": "#Central",
          "BusinessType": "Pub/bar/nightclub",
          "BusinessTypeID": "7843",
          "AddressLine1": "15 Marlborough Crescent",
          "AddressLine2": "Newcastle upon Tyne",
          "PostCode": "NE1 4EE",
          "RatingValue": "AwaitingInspection",
          "RatingKey": "fhrs_awaitinginspection_en-GB",
          "RatingDate": { "-xsi:nil": "true" },
          "LocalAuthorityCode": "416",
          "LocalAuthorityName": "Newcastle Upon Tyne",
          "LocalAuthorityWebSite": "http://www.newcastle.gov.uk/",
          "LocalAuthorityEmailAddress": "psr@newcastle.gov.uk",
          "SchemeType": "FHRS",
          "NewRatingPending": "False",
          "Geocode": {
            "Longitude": "-1.62244200000000",
            "Latitude": "54.96785900000000"
          }
        },

3 个答案:

答案 0 :(得分:1)

我认为你遇到的主要问题是需要解析浮点数。目前它们只是字符串。您可以使用以下功能创建标记。只需将企业作为对象传递给函数,它就会为您创建标记:

   function createMarker(obj) {
        const LatLng = new google.maps.LatLng(
            parseFloat(obj.geocode.Latitude),
            parseFloat(obj.gecode.Longitude)
        );    marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: obj.BusinessName
        });
    }

答案 1 :(得分:1)

尝试将循环更改为:

public struct MyObject: Codable {
    public let creationDate: Date

    enum CodingKeys: String, CodingKey {
        case creationDate = "creation_date"
    }
}


public struct Response<T: Codable>: Codable {
    public let data: T
    public let meta: Meta?
}


public struct Meta: Codable {
    public let count: Int?
}


let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)

let jsonDataSingle: Data = """
    {
        "data": { "creation_date": "2018-04-29 18:00:11" },
        "meta": null
    }
""".data(using: .utf8)!

let jsonDataList: Data = """
    {
        "data": [{ "creation_date": "2018-04-10 17:00:11" }, { "creation_date": "2018-04-29 18:00:11" }],
        "meta": null
    }
""".data(using: .utf8)!

let singleObject = try? decoder.decode(Response<MyObject>.self, from: jsonDataSingle)
dump(singleObject)
let listOfObjects = try? decoder.decode(Response<[MyObject]>.self, from: jsonDataList)
dump(listOfObjects)

答案 2 :(得分:1)

更改循环处理以处理JSON数据中的数组

$.each(jsonData.EstablishmentCollection.EstablishmentDetail, function(key, data) {
  var latLng = new google.maps.LatLng(data.Geocode.Latitude, data.Geocode.Longitude);
  // Creating a marker and putting it on the map
  var marker = new google.maps.Marker({
    position: latLng,
    title: data.BusinessName
  });
  marker.setMap(googleMap);
});

proof of concept fiddle

代码段

html,
body,
#googleMap {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="googleMap"></div>
<script>
  function initialize() {

    var center = new google.maps.LatLng(54.9753905, -1.6236163);
    var mapCanvas = document.getElementById("googleMap");
    var mapOptions = {
      center: center,
      zoom: 12
    };
    var googleMap = new google.maps.Map(mapCanvas, mapOptions);
    $.each(jsonData.EstablishmentCollection.EstablishmentDetail, function(key, data) {
      var latLng = new google.maps.LatLng(data.Geocode.Latitude, data.Geocode.Longitude);
      // Creating a marker and putting it on the map
      var marker = new google.maps.Marker({
        position: latLng,
        title: data.BusinessName
      });
      marker.setMap(googleMap);
    });
  }
</script>
<script>
  var jsonData = {
    "EstablishmentCollection": {
      "EstablishmentDetail": [{
        "FHRSID": "1011573",
        "LocalAuthorityBusinessID": "17/00395/MIXED",
        "BusinessName": "#Central",
        "BusinessType": "Pub/bar/nightclub",
        "BusinessTypeID": "7843",
        "AddressLine1": "15 Marlborough Crescent",
        "AddressLine2": "Newcastle upon Tyne",
        "PostCode": "NE1 4EE",
        "RatingValue": "AwaitingInspection",
        "RatingKey": "fhrs_awaitinginspection_en-GB",
        "RatingDate": {
          "-xsi:nil": "true"
        },
        "LocalAuthorityCode": "416",
        "LocalAuthorityName": "Newcastle Upon Tyne",
        "LocalAuthorityWebSite": "http://www.newcastle.gov.uk/",
        "LocalAuthorityEmailAddress": "psr@newcastle.gov.uk",
        "SchemeType": "FHRS",
        "NewRatingPending": "False",
        "Geocode": {
          "Longitude": "-1.62244200000000",
          "Latitude": "54.96785900000000"
        }
      }]
    }
  }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initialize"></script>