我有一个array
coords = [];
然后我运行这个功能
getVirusData();
function getVirusData() {
getAvailableDatasets()
.then(combineDatasets)
.then(data => { // It's asynchronous
coords.push.apply(coords, data.map(item => item.Lat +"," + item.Long));
});
}
function getAvailableDatasets() {
return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
.then((files) => {
return Promise.all(
files.filter(file => /^time_series_19-covid-.+.csv$/.test(file.name))
.map(file => getDataset(file.download_url))
);
})
.catch(function(err) {
console.log(err);
})
}
function getDataset(url) {
return $.ajax(url)
.then(csv => {
const output = Papa.parse(csv, {
header: true, // Convert rows to Objects using headers as properties
dynamicTyping: true, // Convert some fields to Numbers automatically
});
if (output.data) {
const labelMatches = url.match(/time_series_19-covid-(.+).csv$/);
const label = labelMatches ? labelMatches[1] : "Untitled";
const formatted = output.data.map(area => {
const obj = {};
Object.keys(area).forEach(key => {
if (/^d+/d+/d+$/.test(key)) {
obj[key] = { date: key, [label]: area[key] };
} else {
obj[key] = area[key];
}
});
return obj;
});
return formatted;
} else {
console.log(output.errors);
}
});
}
function combineDatasets(datasets) {
if (datasets.length) {
const combined = datasets.reduce((result, dataset, i) => {
if (i === 0) { return result; }
dataset.forEach(area => {
// Look for area with same coordinates
let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
if (!existingArea) {
result.push(area);
} else {
const dates = Object.keys(area).filter(key => /^d+/d+/d+$/.test(key));
dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
}
});
return result;
}, datasets[0]);
return combined.map(area => {
const obj = { data: [] };
Object.keys(area).forEach(key => {
if (/^d+/d+/d+$/.test(key)) {
obj.data.push(area[key]);
} else {
obj[key] = area[key];
}
});
return obj;
});
} else {
throw "No datasets were found";
}
}
然后,在我将所有值推入数组后,我需要运行这个
drawMarkers();
function drawMarkers() {
for (var a = 0; a < coords.length; ++a) {
var pin = coords[a].split(',');
var latLng = new google.maps.LatLng(pin[0], pin[1]);
var marker = new google.maps.Marker({
position: latLng
});
}
}
在我运行drawMarkers();
的时候,我没有得到任何标记,如果我在for loop
之后console.log(pin)
,我什么都没有得到,因此必须有一个asynchronous
问题
更新完整代码
(function($) {
var markers = [],
circle,
latitude = [],
longitude = [],
datesExternal = [],
links = [],
years = [],
type = [],
coords = [],
oggetti = [],
scuole = [],
privati = [],
markerCluster,
ids = [],
currentSite = [],
author = [],
site = [],
titles = [];
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.600486, lng: 9.261252},
zoomControl: true,
zoom: 2,
minZoom: 2,
maxZoom: 18,
noClear: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
styles: [
{
"featureType": "administrative",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.fill",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.stroke",
"stylers": [
{
"weight": "1.00"
},
{
"color": "#ffffff"
},
{
"visibility": "off"
}
]
},
{
"featureType": "administrative",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "administrative.country",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.country",
"elementType": "geometry.stroke",
"stylers": [
{
"visibility": "on"
}
]
},
{
"featureType": "administrative.country",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.province",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.province",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "administrative.locality",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.neighborhood",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative.neighborhood",
"elementType": "labels.text.fill",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.land_parcel",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"color": "#e2e2e2"
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "landscape",
"elementType": "labels",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "landscape.natural",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "landscape.natural",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#484848"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.local",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"color": "#ededed"
}
]
}
],
draggable: true,
clickable: true,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
scrollwheel: false,
animatedZoom: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false
});
getVirusData();
function getVirusData() {
getAvailableDatasets()
.then(combineDatasets)
.then(data => { // It's asynchronous
coords.push.apply(coords, data.map(item => item.Lat + "," + item.Long));
}).then(function(entry) {
for (var a = 0; a < coords.length; a++) {
var pin = coords[a].split(',');
console.log(pin);
var latLng = new google.maps.LatLng(pin[0], pin[1]);
var marker = new google.maps.Marker({
position: latLng
});
}
});
}
function getAvailableDatasets() {
return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
.then((files) => {
return Promise.all(
files.filter(file => /^time_series_19-covid-.+.csv$/.test(file.name))
.map(file => getDataset(file.download_url))
);
})
.catch(function(err) {
console.log(err);
})
}
function getDataset(url) {
return $.ajax(url)
.then(csv => {
const output = Papa.parse(csv, {
header: true, // Convert rows to Objects using headers as properties
dynamicTyping: true, // Convert some fields to Numbers automatically
});
if (output.data) {
const labelMatches = url.match(/time_series_19-covid-(.+).csv$/);
const label = labelMatches ? labelMatches[1] : "Untitled";
const formatted = output.data.map(area => {
const obj = {};
Object.keys(area).forEach(key => {
if (/^d+/d+/d+$/.test(key)) {
obj[key] = {
date: key,
[label]: area[key]
};
} else {
obj[key] = area[key];
}
});
return obj;
});
return formatted;
} else {
console.log(output.errors);
}
});
}
function combineDatasets(datasets) {
if (datasets.length) {
const combined = datasets.reduce((result, dataset, i) => {
if (i === 0) {
return result;
}
dataset.forEach(area => {
// Look for area with same coordinates
let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
if (!existingArea) {
result.push(area);
} else {
const dates = Object.keys(area).filter(key => /^d+/d+/d+$/.test(key));
dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
}
});
return result;
}, datasets[0]);
return combined.map(area => {
const obj = {
data: []
};
Object.keys(area).forEach(key => {
if (/^d+/d+/d+$/.test(key)) {
obj.data.push(area[key]);
} else {
obj[key] = area[key];
}
});
return obj;
});
} else {
throw "No datasets were found";
}
}
可能是您所引用的脚本不正确。通过运行下面的脚本检查控制台。还将drawMarker
逻辑转移到呼叫的最后。
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
let coords = [];
getVirusData();
function getVirusData() {
getAvailableDatasets()
.then(combineDatasets)
.then(data => { // It's asynchronous
coords.push.apply(coords, data.map(item => item.Lat + "," + item.Long));
}).then(function(entry) {
for (var a = 0; a < coords.length; a++) {
var pin = coords[a].split(',');
console.log(pin);
var latLng = new google.maps.LatLng(pin[0], pin[1]);
var marker = new google.maps.Marker({
position: latLng
});
}
});
}
function getAvailableDatasets() {
return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
.then((files) => {
return Promise.all(
files.filter(file => /^time_series_19-covid-.+.csv$/.test(file.name))
.map(file => getDataset(file.download_url))
);
})
.catch(function(err) {
console.log(err);
})
}
function getDataset(url) {
return $.ajax(url)
.then(csv => {
const output = Papa.parse(csv, {
header: true, // Convert rows to Objects using headers as properties
dynamicTyping: true, // Convert some fields to Numbers automatically
});
if (output.data) {
const labelMatches = url.match(/time_series_19-covid-(.+).csv$/);
const label = labelMatches ? labelMatches[1] : "Untitled";
const formatted = output.data.map(area => {
const obj = {};
Object.keys(area).forEach(key => {
if (/^d+/d+/d+$/.test(key)) {
obj[key] = {
date: key,
[label]: area[key]
};
} else {
obj[key] = area[key];
}
});
return obj;
});
return formatted;
} else {
console.log(output.errors);
}
});
}
function combineDatasets(datasets) {
if (datasets.length) {
const combined = datasets.reduce((result, dataset, i) => {
if (i === 0) {
return result;
}
dataset.forEach(area => {
// Look for area with same coordinates
let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
if (!existingArea) {
result.push(area);
} else {
const dates = Object.keys(area).filter(key => /^d+/d+/d+$/.test(key));
dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
}
});
return result;
}, datasets[0]);
return combined.map(area => {
const obj = {
data: []
};
Object.keys(area).forEach(key => {
if (/^d+/d+/d+$/.test(key)) {
obj.data.push(area[key]);
} else {
obj[key] = area[key];
}
});
return obj;
});
} else {
throw "No datasets were found";
}
}
<script src="https://cdn.jsdelivr.net/npm/papaparse@5.1.1/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
您可以从getVirusData()
返回promise并返回新的coords。
function getVirusData() {
return getAvailableDatasets()
.then(combineDatasets)
.then(data => { // It's asynchronous
coords.push.apply(coords, data.map(item => item.Lat +"," + item.Long));
return coords;
});
}
通过这种方式,您可以将坐标直接传递到drawMarkers()
中,如:
function drawMarkers(coordinates) {
for (var a = 0; a < coordinates.length; ++a) {
var pin = coordinates[a].split(',');
var latLng = new google.maps.LatLng(pin[0], pin[1]);
var marker = new google.maps.Marker({
position: latLng
});
}
}
为了异步传递,您可以在getVirusData()
上使用.then
getVirusData()
.then(coordinates => {
drawMarkers(coordinates);
});