Я пытаюсь изучить простой учебник для разработчиков Google по импорту данных GeoJSON из локального или удаленного источника и отображению их на моей карте. У меня есть код и этот код для данных землетрясения в формате JSON от USGS:
<!DOCTYPE html>
<html>
<head>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<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://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
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 text = ''+results.features[i].properties.place+'';
var latLng = new google.maps.LatLng(coords[1],coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
var infowindow = new google.maps.InfoWindow({
content: text
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
<script async defer
src = "https://maps.googleapis.com/maps/api/js?key=xxxx&callback=initMap">
</script>
</body>
</html>
Код работает нормально, без проблем. Но у меня возникают проблемы с InfoWindows, когда при нажатии на маркер должен открываться и содержать некоторую информацию. Пытаюсь настроить, но не получается. При щелчке нет отверстия в событии щелчка маркера, к которому я прикрепил пример, например название места для этого землетрясения.
Ответ в формате JSON на землетрясение:
{
"type": "FeatureCollection",
"metadata": {
"generated": 1545674780000,
"url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp",
"title": "USGS Magnitude 2.5+ Earthquakes, Past Week",
"status": 200,
"api": "1.7.0",
"count": 326
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 2.6,
"place": "14km WNW of Big Lake, Alaska",
"time": 1545672051177,
"updated": 1545672768461,
"tz": -540,
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ak20539699",
"detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ak20539699.geojsonp",
"felt": null,
"cdi": null,
"mmi": null,
"alert": null,
"status": "automatic",
"tsunami": 0,
"sig": 104,
"net": "ak",
"code": "20539699",
"ids": ",ak20539699,",
"sources": ",ak,",
"types": ",geoserve,origin,",
"nst": null,
"dmin": null,
"rms": 0.82,
"gap": null,
"magType": "ml",
"type": "earthquake",
"title": "M 2.6 - 14km WNW of Big Lake, Alaska"
},
"geometry": {
"type": "Point",
"coordinates": [
-150.2,
61.5832,
17.5
]
},
"id": "ak20539699"
}
]
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Связанный вопрос: Google Maps JS API v3 - пример простого множественного маркера
Ваш прослушиватель событий "click" должен находиться внутри цикла, чтобы его можно было связать с каждым маркером, а контент должен быть связан с маркером (параметр, используемый для этого в соответствующем вопросе, - это закрытие функции):
infowindow = new google.maps.InfoWindow();
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var text = '' + results.features[i].properties.place + '';
var latLng = new google.maps.LatLng(coords[1], coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
marker.addListener('click', (function(marker, text) {
return function(e) {
infowindow.setContent(text);
infowindow.open(map, marker);
}
})(marker, text));
}
доказательство концепции скрипки
фрагмент кода:
var map, infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(2.8, -187.3),
mapTypeId: 'terrain'
});
infowindow = new google.maps.InfoWindow();
// 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://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
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 text = '' + results.features[i].properties.place + '';
var latLng = new google.maps.LatLng(coords[1], coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
marker.addListener('click', (function(marker, text) {
return function(e) {
infowindow.setContent(text);
infowindow.open(map, marker);
}
})(marker, text));
}
}#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}<div id = "map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>