如何使用Google Maps API正确展示爱尔兰郡边界多边形?
Hey there! Let's figure out why some of your Irish county outlines are jumping around on Google Maps—this is a common issue when manually parsing GeoJSON coordinate structures, so we'll get it sorted.
What's Causing the Jump?
Your current code is flattening all coordinate points from every ring (main county outline and any inner "holes" or separate polygon parts) into a single array. Google Maps interprets this as one continuous path, which means it's drawing lines between unrelated points (like from the end of a county's main outline to the start of a hole, or between separate polygons in a MultiPolygon feature). That's exactly why you're seeing those weird jumps.
GeoJSON has strict structure rules:
- For a
Polygontype, coordinates are an array of rings (the first is the main outline, subsequent rings are holes). - For a
MultiPolygontype (common for counties with islands), coordinates are an array of Polygon objects, each with their own rings.
Your code isn't respecting this hierarchy, so it's mixing up independent paths.
Solution 1: Fix Your Coordinate Parsing
Instead of shoving all points into one array, we'll build separate paths for each ring in the GeoJSON. Here's the updated code:
let map; function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 7, center: { lat: 53.411080, lng: -7.710753 }, mapTypeId: "roadmap", }); // Use fetch for async, modern data loading (better than synchronous httpGet) fetch('https://jameswalshe.ie/countiesGEOJSON.geojson') .then(response => response.json()) .then(counties => { counties.features.forEach((feature, s) => { const polygonPaths = []; const coords = feature.geometry.coordinates; // Handle Polygon (single shape with optional holes) if (feature.geometry.type === 'Polygon') { coords.forEach(ring => { const path = ring.map(coord => ({ lat: coord[1], lng: coord[0] })); polygonPaths.push(path); }); } // Handle MultiPolygon (multiple separate shapes, like counties with islands) else if (feature.geometry.type === 'MultiPolygon') { coords.forEach(polygon => { polygon.forEach(ring => { const path = ring.map(coord => ({ lat: coord[1], lng: coord[0] })); polygonPaths.push(path); }); }); } const countyPolygon = new google.maps.Polygon({ paths: polygonPaths, strokeColor: "rgb(0, 139, 63)", strokeOpacity: 1, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0, }); countyPolygon.setMap(map); }); }) .catch(err => console.error('Failed to load GeoJSON:', err)); };
Key changes:
- We check if the feature is a
PolygonorMultiPolygonto handle their different coordinate structures. - Each ring gets its own path array, so Google Maps knows to draw them as independent shapes (not a single connected line).
- Switched to
fetchfor async loading (synchronous requests likehttpGetcan block your page and cause issues).
Solution 2: Use Google Maps Data Layer (Even Easier!)
Instead of manually parsing GeoJSON, let Google Maps handle all the coordinate logic for you with the Data Layer. This is the most reliable approach:
let map; function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 7, center: { lat: 53.411080, lng: -7.710753 }, mapTypeId: "roadmap", }); // Load GeoJSON directly into the Data Layer map.data.loadGeoJson('https://jameswalshe.ie/countiesGEOJSON.geojson'); // Apply your styling map.data.setStyle({ strokeColor: "rgb(0, 139, 63)", strokeOpacity: 1, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0, }); };
This method automatically handles Polygon, MultiPolygon, and hole structures—no manual looping required!
Why This Works
Both solutions respect the GeoJSON's hierarchical structure. The Data Layer is Google's built-in tool for this exact use case, so it's less error-prone than manual parsing. If you need custom logic per county (like hover effects), you can still use the Data Layer with event listeners.
Give either approach a try, and your county outlines should line up perfectly!
内容的提问来源于stack exchange,提问作者james walshe

