问题
I'm currently working on a Google Map, and now I want to "generate" pins from an API. But then I get stuck, because a pin looks like this:
var imageDriver = 'marker.png';
var DriverLatLng = new google.maps.LatLng(location.lat, location.lng);
var driverMarker = new google.maps.Marker({
position: DriverLatLng,
map: map,
icon: imageDriver,
title: drivers[0].name
});
}
I want to create a function of some sort that could "generate" these variables with a prefix. Check an example below:
var imageDriver0;
var DriverLatLng0;
var driverMarker0;
position: DriverLatLng0,
map: map,
icon: imageDriver0,
title: drivers[o].name
These variables must be unique of course so they don't "collide". I have this for-loop that counts all "drivers" inside my API. Could I somehow make this for-loop to create these pins? Example:
driversRealtime();
function driversRealtime() {
setInterval(function () {
var url = "http://blackcab.didair.se/api/drivers";
var lat;
var lon;
var name;
var id;
$.getJSON(url,
function (response) {
for (var i = 0; i < response.drivers.length; i++) //Counts data-elemements inside
lat = response.drivers[i].currentLat;
lon = response.drivers[i].currentLon;
name = response.drivers[i].name;
id = response.drivers[i].profileId;
console.log(lat);
console.log(lon);
console.log(name);
console.log(id);
});
}, 3000); //Delay in milliseconds
}
回答1:
It's possible to create variable names dynamically, but almost always pointless.
Use an array instead or a suffix, and put the values as properties in an object in the array. Example:
var points = [];
var point = {
"url": url,
"lat": lat,
"lng": lng,
"name": name,
"id": id
};
points.push(point);
来源:https://stackoverflow.com/questions/15894755/how-to-generate-unique-variables