You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenLayers 4 用户绘制几何图形坐标提取及投影转换问题求助

Fixing Coordinate Extraction & Projection Issues in OpenLayers 4 Drawing

Hey there, let's work through your OpenLayers 4 drawing and coordinate problems—you're really close, just a couple of key mistakes in how you're handling projections and geometry coordinates!

First, Let's Diagnose the Problems

  1. Invalid Projection Transform Call: Your line new ol.proj.transform(draw, projection, projection2); is trying to transform the draw interaction object itself, which doesn't make sense. ol.proj.transform works on coordinate arrays, not OL objects like interactions. This line is not just useless—it's probably throwing silent errors that mess with your code flow.
  2. Incorrect Coordinate Handling for Complex Geometries: Polygons and LineStrings have nested coordinate structures (Polygon = [[[lon, lat], ...]], LineString = [[lon, lat], ...]), while Points are flat [lon, lat]. Using ol.proj.transform directly on these nested arrays doesn't handle the recursion properly, which is why you're seeing "missing nodes"—the transform isn't processing all the coordinate pairs.

Here's the Fixed Code for Your drawend Event

Replace your problematic event handler with this:

draw.on('drawend', function(evt){
  var feature = evt.feature;
  var geometry = feature.getGeometry();
  
  // OPTION 1: Transform a copy of the geometry (keeps original map geometry in 3857)
  var geometryForCoords = geometry.clone();
  geometryForCoords.transform(projection, projection2);
  
  // OPTION 2: Transform the original geometry (changes what's displayed on the map to 4326)
  // geometry.transform(projection, projection2);
  
  var coordinates = geometryForCoords.getCoordinates();
  var displayText;

  // Format coordinates based on geometry type for readability
  switch(geometry.getType()) {
    case 'Point':
      displayText = `Point Coordinates (EPSG:4326):\n[${coordinates[0].toFixed(6)}, ${coordinates[1].toFixed(6)}]`;
      break;
    case 'LineString':
      displayText = 'LineString Coordinates (EPSG:4326):\n' + 
        coordinates.map(coord => `  • [${coord[0].toFixed(6)}, ${coord[1].toFixed(6)}]`).join('\n');
      break;
    case 'Polygon':
      // Polygons have an outer ring (first array) and optional inner rings
      const outerRing = coordinates[0];
      displayText = 'Polygon Outer Ring Coordinates (EPSG:4326):\n' + 
        outerRing.map(coord => `  • [${coord[0].toFixed(6)}, ${coord[1].toFixed(6)}]`).join('\n');
      break;
    default:
      displayText = JSON.stringify(coordinates, null, 2);
  }

  console.log('Raw Coordinates:', coordinates);
  // Use <pre> to preserve line breaks and formatting
  document.getElementById('point').innerHTML = `<pre>${displayText}</pre>`;
});

Key Changes Explained

  • Use Geometry's Built-in transform Method: OL geometry objects have their own transform() method that automatically handles nested coordinate structures (like Polygon's 3-layer array). This ensures every coordinate pair gets converted, fixing the "missing nodes" issue.
  • Clone Geometry (Optional): If you want to keep the drawn shape in the original EPSG:3857 projection on the map, clone the geometry first before transforming. This way, you only convert the copy for coordinate extraction.
  • Format Coordinates by Type: Different geometry types have different coordinate structures—formatting them based on type makes the output readable instead of a jumbled nested array.
  • Remove the Invalid draw Transform: That line was doing nothing but causing issues, so we got rid of it entirely.

Additional Tips for Storing to GDB via PHP

When sending these coordinates to your PHP backend:

  • Convert the coordinate array to JSON with JSON.stringify(coordinates)
  • Send it via a POST request (avoid GET for large coordinate sets like polygons)
  • In PHP, decode the JSON with json_decode($_POST['coordinates'], true) and then process it for your geodatabase (e.g., convert to WKT if needed)

内容的提问来源于stack exchange,提问作者Benoît 29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:12:33