Google Maps配置问题:从JSON批量添加坐标至features变量失败
Fixing Google Maps Marker Loading from JSON Data
Hey there, let's sort out this issue with loading markers from your JSON data into Google Maps. I see two key problems in your current code, and I'll walk you through fixing them step by step.
Core Issues in Your Current Code
- Asynchronous Timing Problem: The
$.getJSONrequest runs asynchronously—meaning your code tries to accessmyjson.resultsbefore the JSON data has actually been fetched. At that point,myjsonis still undefined, so the loop does nothing. - Empty Traversal Logic: Your
myjson.results.forEachblock is empty—you're not actually converting the JSON coordinates into map-friendly objects and adding them to thefeaturesarray.
Corrected Full Script
Here's the revised code that addresses both issues:
<script> var map; function initMap() { map = new google.maps.Map(document.getElementById('mapGoogle'), { zoom: 7, center: new google.maps.LatLng(51.509865, -0.118092), mapTypeId: 'roadmap', gestureHandling: 'greedy', disableDefaultUI: true }); var icons = { info: { icon: 'http://www.picpng.com/uploads/small/Google_Map_Marker_Red_Peg_77453.Png' } }; // Move all JSON processing inside the getJSON callback to ensure data is loaded $.getJSON("http://app.regain-app.com/rest/V1/points/get?lat=50.164001&lng=-5.069998&distance=26", function(json){ var features = []; // Traverse the results array and build features json.results.forEach(function(item){ // Convert lat/lng from string to number (required by Google Maps) var lat = parseFloat(item.lat); var lng = parseFloat(item.lng); features.push({ position: new google.maps.LatLng(lat, lng), type: 'info' }); }); // Create markers now that features is populated features.forEach(function(feature) { var marker = new google.maps.Marker({ position: feature.position, icon: icons[feature.type].icon, map: map }); }); }); } </script>
Key Changes Explained
- Moved Logic to Callback: All code that relies on the JSON data (building
featuresand creating markers) is now inside the$.getJSONcallback function. This ensures we only process the data after it's successfully fetched. - Converted String Coordinates: The JSON returns
latandlngas strings—we useparseFloat()to convert them to numerical values, whichgoogle.maps.LatLngrequires to work correctly. - Populated Features Array: The
forEachloop now actually creates a feature object for each result in the JSON and adds it to thefeaturesarray.
This should load all your markers from the JSON data onto the Google Map correctly!
内容的提问来源于stack exchange,提问作者Morgan
相关产品推荐
相关产品推荐

