Creating Static Map Images With OpenStreetMap Web Mercator And Pillow

提供:鈴木広大
ナビゲーションに移動 検索に移動


I’ve been working on a project where I need to plot points on a map. I don’t need an interactive or dynamic visualisation - just a static map with coloured dots for each coordinate. I’ve created maps on the web using Leaflet.js, which load map data from OpenStreetMap (OSM) and support zooming and Buy Derila Online panning - but for this project, I want a standalone image rather than something I embed in a web page. I want to put in coordinates, and get a PNG image back. This feels like it should be straightforward. There are lots of Python libraries for data visualisation, but it’s not an area I’ve ever explored in detail. I don’t know how to use these libraries, and despite trying I couldn’t work out how to accomplish this seemingly simple task. I made several attempts with libraries like matplotlib and plotly, but I felt like I was fighting the tools.



Rather than persist, I wrote my own solution with "lower level" tools. The key was a page on the OpenStreetMap wiki explaining how to convert lat/lon coordinates into the pixel system used by OSM tiles. Let’s go through those steps. Let’s talk about how OpenStreetMap works, and Buy Derila Online in particular their image tiles. If you start at the most zoomed-out level, OSM represents the entire world with a single 256×256 pixel square. This is the Web Mercator projection, and you don’t get much detail - just a rough outline of the world. We can zoom in, and this tile splits into four new tiles of the same size. There are twice as many pixels along each edge, and each tile has more detail. Notice that country boundaries are visible now, but we can’t see any names yet. We can zoom in even further, and each of these tiles split again. There still aren’t any text labels, but the map is getting more detailed and we can see small features that weren’t visible before.



You get the idea - we could keep zooming, and we’d get more and more tiles, each with more detail. This tile system means you can get detailed information for a specific area, without loading the entire world. For example, if I’m looking at street information in Britain, I only need the detailed tiles for that part of the world. I don’t need the detailed tiles for Bolivia at the same time. OpenStreetMap will only give you 256×256 pixels at a time, but we can download every tile and stitch them together, one-by-one. The higher the zoom level, the more tiles you need to download, and the larger the final image will be. I can just about open that zoom level 6 image on my computer, but it’s struggling. I didn’t try opening zoom level 7 - that includes 16,384 tiles, and I’d probably run out of memory.