使用map()函数处理CSV坐标绘图时遇错误求助
Hey there, let's break down what's going wrong here and fix it step by step!
First off, those converted coordinate values look super suspicious—your max/min Lat and Long are almost identical (like maxLat = 198987.05 vs minLat = 198986.94). That's way too small a range for proper Web Mercator coordinates, which should span millions of units (e.g., x values from ~-20 million to 20 million for longitude, y values similarly for latitude). This tiny range is definitely why your map() function is failing (you might even be hitting a division-by-zero error if max and min are equal in edge cases).
Let's diagnose the root causes first:
- Did you accidentally convert already-converted coordinates?
If your original CSV data was already in Web Mercator format (not raw WGS84 latitude/longitude in decimal degrees), running the conversion formula again would squish the values into this tiny, useless range. Double-check your raw data: raw latitudes should be between -90 and 90, longitudes between -180 and 180. - Did you mess up the Web Mercator formula?
It's easy to mix up radians/degrees, or flip lat/lon, or use the wrong constants. Here's the correct implementation for WGS84 decimal degrees (using Python as an example):
Key notes here: you must use radians for trigonometric functions, and the constantimport math def convert_to_web_mercator(lat, lon): # Convert latitude to y y = math.log(math.tan((90 + lat) * math.pi / 360)) * 20037508.34 / math.pi # Convert longitude to x x = lon * 20037508.34 / 180 return x, y20037508.34is half the circumference of the Earth at the equator (which Web Mercator uses as its scale). - Did you swap latitude and longitude in your code?
If you plugged lat values into the longitude formula and vice versa, you'd get weirdly constrained values like what you're seeing.
Once you fix the conversion, fix the mapping step:
Even after getting valid Web Mercator coordinates, you need to handle edge cases where max and min are identical (though this shouldn't happen with real spatial data). Here's a safe map() function implementation:
def map_coordinate(value, original_min, original_max, new_min=0, new_max=500): if original_max == original_min: # Avoid division by zero—return the middle of the target range return (new_min + new_max) / 2 return (value - original_min) * (new_max - new_min) / (original_max - original_min) + new_min
Quick action items to test:
- Print out 5-10 raw latitude/longitude rows from your CSV to confirm they're in decimal degrees (e.g.,
lat: 40.7128, lon: -74.0060for NYC). - Run the correct conversion formula on those raw values and check the output—you should get x/y values in the millions.
- Recalculate your max/min values after fixing the conversion, then run the safe mapping function.
That should get your coordinates plotting correctly on your 0-500 canvas!
内容的提问来源于stack exchange,提问作者John Smith

