Я бы предложил передать координаты и заголовок (текст при наведении курсора) в функции (вместо того, чтобы рассчитывать на глобальные переменные для работы).
Вам потребуются две функции:
- a
createMarker
функция (заменяет вашу draw
функцию). - a
GeocodeMarker
функция (заменяет вашу Geocoding
функцию).
function createMarker(markerCoords, date){
var image = 'images/Logo/virus.png';
var marker = new google.maps.Marker({
title: date,
position: markerCoords,
map: map,
icon: image
});
}
function GeocodeMarker(address, date){
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
markerCoords =results[0].geometry.location;
createMarker(markerCoords, date);
} else {
alert("Can't geocode: "+address+", status="+status);
}
});
}
подтверждение концепции скрипта
фрагмент кода:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
showOccurrences();
}
function showOccurrences() {
var geocoder;
var address;
var markerCoords;
var locations;
var dates;
var recorded;
var a = ["10007", "07102", "07649"]; // <?php echo json_encode($a); ?>;
var b = ["1/1/2000", "2/2/2001", "3/3/2003"]; // <?php echo json_encode($b); ?>;
console.log(a);
console.log(b);
var Worcester = {
lat: 52.188,
lng: -2.220
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: Worcester
});
while (a.length > 0 && b.length > 0) { //while the postcode array still has postcodes in it
locations = a[0]; //value of the last postcode in the array
dates = b[0];
geocoder = new google.maps.Geocoder();
address = locations;
GeocodeMarker(a[0], b[0]);
a.shift();
b.shift();
console.log(locations);
console.log(dates);
}
var bounds = new google.maps.LatLngBounds();
function GeocodeMarker(address, date) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
markerCoords = results[0].geometry.location;
createMarker(markerCoords, date);
} else {
alert("Can't geocode: "+address+", status="+status);
}
});
}
function createMarker(markerCoords, date) {
console.log(markerCoords, date);
var image = 'images/Logo/virus.png';
marker = new google.maps.Marker({
title: date,
position: markerCoords,
map: map,
});
}
}
/* 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;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>