my problem is that measured length or area with openlayers api has difference with the real one, for example a 55.30 meter length is 50.13 m in my web app. my data are in "projected UTM WGS84 Zone 40" coordinate system and I am using openlayers js api v:"7.5.1" in react. Thanks in advance.
Note 1: base on openlayers documents, geometry.getLength() and geometry.getArea() methods return measures of projected (planar) geometries.
// this is a part of defined map in CreateMap component:
useEffect(() => { if(mapRef.current) {
const centerUTM = [253610, 2867476]
const map = new Map({
target: mapRef.current,
layers: [
new TileLayer({
//source: new OSM(),
}),
],
view: new View({
projection: "EPSG:32640",
center: centerUTM,
zoom: 20, // Initial zoom level
}),
})
props.setMap(map)
return () => {
map.setTarget(null)
}
}}, [])
// follow is part of my GeometryCalculate to measure a length or area:
const source = new VectorSource();
const vector = new VectorLayer({
source: source,
style: vectorStyle,
});
vectorLayersRef.current.push(vector);
map.addLayer(vector);
draw = new Draw({
source: source,
type: drawingType,
stopClick: true,
});
let sketch;
let tooltipCoord;
draw.on('drawstart', (evt) => {
setIsDrawing(true); // Set isDrawing to true when drawing starts
// Create a new measure tooltip element
const measureTooltipElement = document.createElement('div');
measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
// Create a new measure tooltip overlay
const measureTooltip = new Overlay({
element: measureTooltipElement,
offset: [0, -15],
positioning: 'bottom-center',
stopEvent: false,
insertFirst: false,
});
// Add the measure tooltip overlay to the map
map.addOverlay(measureTooltip);
sketch = evt.feature;
sketch.getGeometry().on('change', function (evt) {
const geom = evt.target;
let output;
if (geom instanceof Polygon) {
output = formatArea(geom);
tooltipCoord = geom.getInteriorPoint().getCoordinates();
} else if (geom instanceof LineString) {
output = formatLength(geom);
tooltipCoord = geom.getLastCoordinate();
}
measureTooltipElement.innerHTML = output;
measureTooltip.setPosition(tooltipCoord);
});
});
draw.on('drawend', () => {
setIsDrawing(false); // Set isDrawing to false when drawing ends
});
map.addInteraction(draw);
drawInteractionRef.current = draw;
const formatLength = function (line) {
const length = getLength(line);
let output;
if (length > 100) {
output = `${Math.round((length / 1000) * 100) / 100} km`;
} else {
output = `${Math.round(length * 100) / 100} m`;
}
return output;
};
const formatArea = function (polygon) {
const area = getArea(polygon);
let output;
if (area > 10000) {
output = `${Math.round((area / 1000000) * 100) / 100} km²`;
} else {
output = `${Math.round(area * 100) / 100} m²`;
}
return output;
};