2017-02-09 36 views
0
這樣

我有數據:迭代通過響應的數據來創建谷歌地圖對象

"meta":{"About thisdata"}, "objects": [{"beat": "1614", "block": "081XX W HIGGINS RD", "case_number": "JA100466", "classification": "/api/1.0-beta3/crimeclassification/83/", "community_area": "/api/1.0-beta3/communityarea/10/", "community_name": "Norwood Park", "community_number": 10, "community_slug": "norwood-park", "crime_date": "2016-12-30T18:00:00", "description": "$500 AND UNDER", "domestic": false, "fbi_code": "06", "id": "10801504", "iucr": "0820", "latitude": 41.985421498, "location_description": "STREET", "longitude": -87.829756604, "primary_type": "THEFT", "ward": 41, "year": 2016}, 

總的說來,這將有500個對象,在「對象」

我想創建的這500:new google.maps.LatLng(37.782551, -122.445368)

把陣列中的是這樣的:

function getPoints() { 
     return [ 
      new google.maps.LatLng(37.782551, -122.445368), 
      new google.maps.LatLng(37.782745, -122.444586), 
      new google.maps.LatLng(37.782842, -122.443688) 

     ] 
} 

要返回在這裏:

function initMap() { 
    map = new google.maps.Map(document.getElementById("map"), { 
    center: { lat: 41.881, lng: -87.629 }, 
    zoom: 12, 
    mapTypeId: 'satellite' 
    }); 

    heatmap = new google.maps.visualization.HeatmapLayer({ 
    data: makeMarkers(), <-- Here 
    map: map 
    }); 
} 

的代碼我已經試過這個樣子的:

var makeMarkers = function() { 
    var result = []; 
    var lat, lng = []; 
    resp.objects.forEach(function(objects) { 
    lat.objects.latitude; 
    lng = objects.longitude; 
    return [new google.maps.LatLng(lat, lng)] 
}) 
} 

而不是返回新對象的數組,但是,它會返回500個的新陣列,一個谷歌的對象,因爲它是在foreach內。我不知道如何得到我要找的東西。我在範圍內反覆爭取數據。

謝謝!

回答

1

我假設resp對象是您帖子頂部的對象。首先,你需要在陣列上使用map來實際返回數組。

地圖

地圖,因爲它的作用在陣列中的每個元素上的工作原理類似的forEach。區別在於,在回調到map之後,您將返回更新的元素。

例:

[1, 2, 3, 4].map(function (element) { 
    return element * 2 
} 

上面與返回的數組如下:[2, 4, 6, 8]。 請注意回調方法中的返回值。

對於你的情況

你想從你的respmap每個這些元素在谷歌地圖的對象(即google.maps.LatLng(lat, lng)

得到objects陣列如果我理解你是正確什麼試圖做到,以下應該工作。我建議玩弄map(也有filter,forEachreducefoldr在某些語言)的更簡單的例子很容易知道)。

var makeMarkers = function() { 
    var result = []; 
    var lat, lng = []; 
    return resp.objects.map(function(element) { 
    lat = element.latitude; 
    lng = element.longitude; 
    return new google.maps.LatLng(lat, lng); 
    }) 
} 
+0

嗯我不知道我是否足夠好地解釋了我自己。我會更簡潔。我試圖從500個對象中取出所有的Lat和Lng,並在這裏創建一個500個像'googe.LatLng(Latitude,Longitude)''''googe'文檔 - > https://開發者.google.com/maps/documentation/javascript/examples/layer-heatmap – Quesofat

+0

在這種情況下,上面應該這樣做。對於'objects'數組的每個元素,拉出lat/lng並創建一個新的Google Maps對象。它們都映射到一個數組並返回。 –

+0

錯誤。我已經有你的意思了? – Quesofat