文档章节

Mapnik教程-使用Python创建地图

openthings
 openthings
发布于 2016/04/24 22:50
字数 1473
阅读 757
收藏 0

Mapnik教程-使用Python创建地图

Tutorial 1 -- Getting started in Python

Overview

This tutorial will ensure that Mapnik and its Python bindings are properly installed and introduce you to some of the basic programming concepts for Mapnik.

Step 1: check installation

Make sure you have mapnik installed. You should be able to open a terminal and type:

mapnik-config -v # should return a version number.

This tutorial expects Mapnik 2.x or greater. Older versions do not provide the mapnik-config program, so we recommend upgrading.

Please note that if you are using mapnik 2.0.0 then you will need to adjust the "mapnik" module name to "mapnik2" in the Python commands. Refer to mapnik2 for details of the naming convention.

Please also note that unlike Mapnik 2.x, version 3.x does not include Python bindings anymore. You can find the new Python bindings here.

Next test the Python bindings. You should be able to open a terminal and type:

python -c "import mapnik;print mapnik.__file__" # should return the path to the python bindings and no errors

If the above does not work (e.g. throws an ImportError) then please go back and ensure Mapnik is properly installed. If you need help, sign up for the mailing list to ask questions or join the #mapnik room on freenode IRC

Step 2

Now, we need some data to render. Let's use a shapefile of world border polygons from http://naturalearthdata.com. Download the data from this wiki's local cache here or directly from the Natural Earth Data site. Unzip the archive in an easily accessible location of your choosing. In Step 3 we will be referencing the path to this shapefile in Python code, so make sure you know where you put it.

Once unzipped, you should see four files like:

ne_110m_admin_0_countries.shp
ne_110m_admin_0_countries.shx
ne_110m_admin_0_countries.dbf
ne_110m_admin_0_countries.prj

To download and unzip on the command line with the do:

wget https://github.com/mapnik/mapnik/wiki/data/110m-admin-0-countries.zip
unzip 110m-admin-0-countries.zip # creates ne_110m_admin_0_countries.shp

Step 3

Now we're going to program in Python and Mapnik, using sample code and the Python interpreter.

The idea here is not that you have to interact with Mapnik via Python, but that this is a good way to build foundational skills for how Mapnik works.

So, let's begin! Open a Python interpreter simply by typing in your terminal:

python

The code below can be pasted into your interpreter. Ideally paste line by line so you can confirm each step is working. The commented lines (#) should be able to be pasted without trouble, but depending on your interpreter setting may cause errors.

Import Mapnik

Import the Mapnik Python bindings:

import mapnik

Create a Map

m = mapnik.Map(600,300) # create a map with a given width and height in pixels# note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'# the 'map.srs' is the target projection of the map and can be whatever you wish m.background = mapnik.Color('steelblue') # set background colour to 'steelblue'.

Create a Style

Create the Styles which determines how the data is rendered:

s = mapnik.Style() # style object to hold rulesr = mapnik.Rule() # rule object to hold symbolizers# to fill a polygon we create a PolygonSymbolizerpolygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
r.symbols.append(polygon_symbolizer) # add the symbolizer to the rule object# to add outlines to a polygon we create a LineSymbolizerline_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)
r.symbols.append(line_symbolizer) # add the symbolizer to the rule objects.rules.append(r) # now add the rule to the style and we're done

And add the Style to the Map:

m.append_style('My Style',s) # Styles are given names only as they are applied to the map

Create a Datasource

In Step 2 above you should have downloaded a sample shapefile of polygons of world countries. We are now going to load that into a mapnik.Datasource object in Python.

If your Python interpreter was launched from the same directory as you downloaded the natural earth shapefile to you should be able to use a relative path to create the datasource like:

ds = mapnik.Shapefile(file='ne_110m_admin_0_countries.shp')

Otherwise use an absolute path (exchanging /Users/dane/Downloads/ for the correct path on your machine):

ds = mapnik.Shapefile(file='/Users/dane/Downloads/ne_110m_admin_0_countries.shp')

Note: optionally (to learn about your data) you can call the envelope() function off the datasource object to see the full coordinate bounds of the data:

>>> ds.envelope()
Box2d(-180.0,-90.0,180.0,83.64513)

That shows the minx, miny, maxx, and maxy of the data. Because the above coordinates are between -180 and 180 for the x or longitude values and -90 and 90 for the y or latitude values we know this data is in geographic coordinates and uses degrees for units - a pretty good indication this is WGS84 (aka EPSG:4326). This specific shapefile also stores this projection information as a WKT string in the ne_110m_admin_0_countries.prj file. See the layer.srs value below for why this matters.

Create a Layer

Mapnik Layers are basically containers around datasources, that store useful properties. Lets now create a Layer object and add the datasource to it.

layer = mapnik.Layer('world') # new layer called 'world' (we could name it anything)# note: layer.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'

Note: the 'layer.srs' is the source projection of the Datasource and must match the projection of the coordinates of that data or else your map will likely be blank. Mapnik uses Proj.4 strings to specify the spatial references system. In this case, the default srs Mapnik assumes (+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs) happens to match the projection of the data. When this is not the case you must set the layer.srs to the correct value (which is beyond the scope of this tutorial).

Now attach the datasource to the layer, and reference:

layer.datasource = ds

Lastly, we need to make sure the style we created above (and attached to the map) is also applied to the layer, by its string reference:

layer.styles.append('My Style')

Prepare the Map for rendering

This step is critical. Finally add the layer to the map and zoom to the full extent of the data layer (using zoom_all which will calculate the cumulative extent of all layers attached to the map). If you do not zoom the Map to the extent of the layer(s), then the rendered output will be blank.

m.layers.append(layer)
m.zoom_all()

Render your map

Finish up by rendering your map image:

# Write the data to a png image called world.png in the current directorymapnik.render_to_file(m,'world.png', 'png')# Exit the Python interpreterexit() # or ctrl-d

Then back in your normal shell type:

# On a macopen world.png# On windowsstart world.png

Or navigate to your base directory and open world.png and the result should look like this: ![world.png]

Step 4

The next logical step is to run that same code all at once as a Python script from your shell/terminal (rather than pasted into the Python interpreter line-by-line). This way you will be able to modify and experiment with the settings, then simply re-run the script.

So, create a blank text file called world.py.

Make it executable:

chmod +x world.py

Then add a line at the top of the script like:

#!/usr/bin/env python

Finally, append the entire text below and save the file.

import mapnik
m = mapnik.Map(600,300)
m.background = mapnik.Color('steelblue')
s = mapnik.Style()
r = mapnik.Rule()
polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
r.symbols.append(polygon_symbolizer)
line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)
r.symbols.append(line_symbolizer)
s.rules.append(r)
m.append_style('My Style',s)
ds = mapnik.Shapefile(file='ne_110m_admin_0_countries.shp')
layer = mapnik.Layer('world')
layer.datasource = ds
layer.styles.append('My Style')
m.layers.append(layer)
m.zoom_all()
mapnik.render_to_file(m,'world.png', 'png')print "rendered image to 'world.png'"
  • Don't forget to ensure the correct path to your ne_110m_admin_0_countries.shp shapefile.

  • Mapnik accepts both the absolute path to your data as well as the relative path (Same goes for the path to where you want to save your file)

Finally run the script with the command:

./world.py # You must be in the same directory as you saved the script
  • Note: if you re-run this script it will will re-write over the world.png map.

  • Now you can easily open the script in a separate text editor and try changing the dimensions, colors, or datasource (remember to use the correct srs if you change the datasource).


本文转载自:https://github.com/mapnik/mapnik/wiki/GettingStartedInPython

openthings
粉丝 325
博文 1140
码字总数 689435
作品 1
东城
架构师
私信 提问
离线地图解决方案一

离线地图使用私有OSM Server作为Tile服务器, 前端使用Openlayer渲染地图数据. 共实践了两种安装环境(准确来说是三种, 但是放弃了在Redhat 6.5的部署...). Ubuntu 16.04 安装介绍 环境 名称 ...

c_mobie
2016/08/06
272
0
mapnik试用调研

0、之前在ubuntu14.04中,因为某些原因,mapnik安装有问题,影响了后续进程 next:熟悉mapnik的使用,搞懂其基本原理,打通相关关节 1、在mac中安装mapnik,遇到了些问题 1.1、brew直接安装,...

有待分裂的人格们
2016/06/15
97
0
[雪峰磁针石博客]flask构建自动化测试平台6-交互式犯罪地图

6-交互式犯罪地图 本章将介绍以下主题: mysql 创建犯罪地图 本文最新版本 代码地址 安装mysql dbconfig.py db_setup.py crimemap.py dbhelper.py home.html 可爱的python测试开发库 请在git...

Python测试开发人工智能
2018/07/11
0
0
2018最后一个月的Python热文Top10!赶紧学起来~

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dQCFKyQDXYm3F8rB0/article/details/85219496 作者 | Mybridge 译者 | linstancy 整理 | Jane 出品 | AI科技大...

AI科技大本营
2018/12/22
0
0
Mapbox Studio 常见问题

之前借助leaflet +qunee实现了地图拓扑图,同样使用leaflet的有个更专业的地图应用:Mapbox,可以定制出简单、专业、漂亮的地图,在传统地图服务商(Google,Nokia, Apple ...)之外,有了更...

nosand
2014/12/01
10.1K
0

没有更多内容

加载失败,请刷新页面

加载更多

为构建社交关系链手淘都做了啥?

作者|王卫(泓冰) 出品|阿里巴巴新零售淘系技术部 01、淘宝社交关系推荐的背景 1、互联网下半场到来:互联网的下半场,人口红利消失,各大平台需要对用户做精细化运营,用户的增长和留存是每一...

阿里云官方博客
20分钟前
3
0
Iaas/Paas/Saas有何区别,一个故事告诉你

云计算有三种服务模式,IaaS,PaaS和SaaS。单从英文全称去理解,他们分别是“基础设施即服务”“平台即服务”和“软件即服务”。 这样翻译过来可不好理解,但是我们可以举个例子。现在我们就以...

JEPaaS云平台
28分钟前
4
0
温度传感器怎么测好坏

  温度传感器也就是负温度系数热敏电阻,温度越高,电阻越小,测量时先看其阻值能不能根据温度的变化而变,再看其变化的阻值是不是在标定的范围之内。   有以下四种方法;   1、若是有...

仙溪
28分钟前
3
0
zk中ZooKeeperServer解析

内部类 ChangeRecord 处理PrepRP和FinalRP之间的信息 static class ChangeRecord { ChangeRecord(long zxid, String path, StatPersisted stat, int childCount, List<ACL> acl) {......

writeademo
39分钟前
3
0
LNMP---安装worrdpress、discuz,域名重定向,用户认证,nginx访问日志

4.34 安装wordpress 4.35 安装discuz 4.36 域名重定向 4.37 用户认证 4.38 nginx访问日志 一、安装wordpress 创建博客: 添加一个博客的虚拟主机 blog.tobe.com.conf 做如下更改 安装博客wor...

tobej
40分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部