基于JSON坐标的地图标记批量生成自动赋值问题求助
Hey there! Let's ditch that tedious manual setup and get your code to automatically fill the markers array based on how many coordinate entries are in your JSON file. Here are a few straightforward, practical methods you can use:
First, let's assume your parsed JSON data looks like this
Adjust this if your actual JSON has a different structure (like a wrapper object), but this is a common format for coordinate datasets!
[ {"lng": 120.1234, "lat": 30.5678}, {"lng": 121.9012, "lat": 31.3456}, {"lng": 122.7890, "lat": 32.1234} ]
Method 1: Traditional for Loop
If you prefer a classic, easy-to-follow approach, this works reliably for any array length:
// Assume your parsed JSON data is stored in this variable const jsonCoordinateData = [/* your parsed JSON entries */]; const markers = []; for (let i = 0; i < jsonCoordinateData.length; i++) { const currentEntry = jsonCoordinateData[i]; // Push the lng/lat values into markers—add extra properties here if needed markers.push({ lng: currentEntry.lng, lat: currentEntry.lat }); }
Method 2: forEach Loop
A more readable, concise option that iterates directly over each JSON entry:
const jsonCoordinateData = [/* your parsed JSON entries */]; const markers = []; jsonCoordinateData.forEach(entry => { markers.push({ lng: entry.lng, lat: entry.lat }); });
Method 3: map Method (Most Clean & Concise)
This method creates the markers array in one step by transforming each JSON entry—perfect for keeping your code tidy:
const jsonCoordinateData = [/* your parsed JSON entries */]; const markers = jsonCoordinateData.map(entry => ({ lng: entry.lng, lat: entry.lat }));
All three methods will automatically adapt to the number of entries in your JSON file—no more manual index assignment! If your JSON has extra properties you want to include in the markers array, just add them to the object being pushed or returned.
内容的提问来源于stack exchange,提问作者Cenk Camkıran

