├── .gitignore
├── ReadMe.rst
├── ReadMe_CN.rst
├── debian_install.sh
├── figures.py
├── gispy_helper
└── __init__.py
├── part010
├── __init__.py
├── ch01_introduction
│ ├── __init__.py
│ ├── sec1_gis
│ │ ├── __init__.py
│ │ ├── test_1_GIS.py
│ │ ├── test_2_position_distance_x_x.py
│ │ ├── test_fig_bianxing.py
│ │ ├── test_fig_distance.py
│ │ ├── test_fig_earth.py
│ │ ├── test_fig_point_demo.py
│ │ ├── test_fig_point_demo.xml
│ │ └── test_fig_proj.py
│ ├── sec2_data
│ │ ├── __init__.py
│ │ └── test_3_vector_type_x_x.py
│ ├── sec3_software_install_and_setup
│ │ ├── __init__.py
│ │ ├── test_2_install_under_Debian_x_x.py
│ │ └── test_fig_gis_libs.py
│ ├── sec4_python
│ │ ├── __init__.py
│ │ ├── test_1_intro_x_x.py
│ │ ├── test_2_structure_x_x.py
│ │ ├── test_3_flow_x_x.py
│ │ └── test_4_list_str_x_x.py
│ └── sec5_this_book
│ │ ├── __init__.py
│ │ └── test_1_codes_style_x_x.py
├── ch02_gdal
│ ├── __init__.py
│ ├── chapter_x_x.py
│ ├── sec1_gdal_intro
│ │ ├── __init__.py
│ │ └── test_2_datamodel_x_x.py
│ ├── sec2_dataset
│ │ ├── __init__.py
│ │ ├── test_1_using_gdal_x_x.py
│ │ ├── test_2_img_info_x_x.py
│ │ └── test_3_band_x_x.py
│ ├── sec3_reading_data
│ │ ├── __init__.py
│ │ ├── test_1_band_data_type_x_x.py
│ │ ├── test_2_access_dataset_data_x_x.py
│ │ └── test_3_reading_band_data_x_x.py
│ ├── sec4_create_raster
│ │ ├── __init__.py
│ │ ├── section_x_x.py
│ │ ├── test_1_create_copy_x_x.py
│ │ ├── test_2_create_x_x.py
│ │ ├── test_3_create_mul_bands_x_x.py
│ │ ├── test_4_write_sr_x_x.py
│ │ └── test_5_pyramids_x_x.py
│ └── sec5_gdal_others
│ │ ├── __init__.py
│ │ ├── test_1_gdal_pillow_x_x.py
│ │ ├── test_2_gdal_tools_x_x.py
│ │ ├── test_3_index_img_x_x.py
│ │ ├── test_4_map_algebra_x_x.py
│ │ └── test_5_affine_x_x.py
├── ch03_ogr
│ ├── __init__.py
│ ├── sec1_ogr_intro
│ │ ├── __init__.py
│ │ └── test_1_command_tools_x_x.py
│ ├── sec2_reading
│ │ ├── __init__.py
│ │ ├── test_1_import_x_x.py
│ │ ├── test_2_datasource_x_x.py
│ │ ├── test_3_layer_x_x.py
│ │ ├── test_4_feature_x_x.py
│ │ ├── test_5_sr_x_x.py
│ │ └── test_fig_ogr_reading.py
│ ├── sec3_writing
│ │ ├── __init__.py
│ │ ├── test_1_Create_Shapefile_x_x.py
│ │ ├── test_2_create_geom_x_x.py
│ │ ├── test_3_create_file_x_x.py
│ │ ├── test_4_create_data_x_x.py
│ │ ├── test_5_field_x_x.py
│ │ └── test_6_projection_x_x.py
│ ├── sec4_filter
│ │ ├── __init__.py
│ │ ├── help_fig_ogr_filter.py
│ │ ├── test_1_filter_attr_x_x.py
│ │ ├── test_2_filter_spatial_x_x.py
│ │ ├── test_3_using_SQL_x_x.py
│ │ ├── test_4_application.py
│ │ ├── test_fig_filter_attr.py
│ │ └── test_fig_filter_spatial.py
│ └── sec5_fiona
│ │ ├── __init__.py
│ │ ├── test_1_intro_x_x.py
│ │ ├── test_2_reading_x_x.py
│ │ └── test_3_schema_x_x.py
├── ch04_proj
│ ├── __init__.py
│ ├── sec1_fundation
│ │ ├── __init__.py
│ │ └── test_3_concepts_in_proj4_x_x.py
│ ├── sec2_proj_command
│ │ ├── __init__.py
│ │ ├── test_1_proj_command_x_x.py
│ │ ├── test_2_proj_setup_x_x.py
│ │ ├── test_3_cs2cs_x_x.py
│ │ ├── test_4_geod_x_x.py
│ │ └── test_fig_ls2cc.py
│ ├── sec3_pyproj
│ │ ├── __init__.py
│ │ ├── test_1_Proj_x_x.py
│ │ ├── test_2_transform_x_x.py
│ │ ├── test_3_geod_x_x.py
│ │ └── test_fig_ls2cc_npts.py
│ └── sec4_osr_basic
│ │ ├── __init__.py
│ │ ├── test_2_def_geo_coor_x_x.py
│ │ ├── test_3_query_coor_x_x.py
│ │ ├── test_4_sr_from_file_x_x.py
│ │ └── test_5_proj_x_x.py
├── ch05_shapely
│ ├── __init__.py
│ ├── sec1_introduction
│ │ ├── __init__.py
│ │ └── test_3_quick_start_x_x.py
│ ├── sec2_geometry_opt
│ │ ├── __init__.py
│ │ ├── test_1_general_funcs_x_x.py
│ │ ├── test_2_simple_geometry_x_x.py
│ │ ├── test_3_collects_x_x.py
│ │ ├── test_fig_buffer.py
│ │ ├── test_fig_geometrycollection.py
│ │ ├── test_fig_linearring.py
│ │ ├── test_fig_linestring.py
│ │ ├── test_fig_multilinestring.py
│ │ ├── test_fig_multipolygon.py
│ │ └── test_fig_polygon.py
│ ├── sec3_predicates
│ │ ├── __init__.py
│ │ ├── test_1_one_element_pre_x_x.py
│ │ ├── test_2_tow_elements_pre_x_x.py
│ │ └── test_3_de9im_x_x.py
│ ├── sec4_spatial_analysis
│ │ ├── __init__.py
│ │ ├── test_1_sets_x_x.py
│ │ ├── test_2_gen_new_fea_x_x.py
│ │ ├── test_fig_MBR.py
│ │ ├── test_fig_buffer.py
│ │ ├── test_fig_convex_hull.py
│ │ ├── test_fig_difference.py
│ │ ├── test_fig_intersection-sym-difference.py
│ │ ├── test_fig_simplify.py
│ │ └── test_fig_union.py
│ ├── sec5_operate
│ │ ├── __init__.py
│ │ ├── test_1_join_lines_x_x.py
│ │ ├── test_2_cascaded_union_x_x.py
│ │ ├── test_3_prep_x_x.py
│ │ ├── test_fig_cascaded_union.py
│ │ └── test_fig_opt_lines.py
│ └── sec6_interop
│ │ ├── __init__.py
│ │ ├── test_1_wkt_x_x.py
│ │ ├── test_2_numpy_x_x.py
│ │ └── test_3_geo_inter_x_x.py
├── ch06_spatialite
│ ├── __init__.py
│ ├── sec1_concept
│ │ ├── __init__.py
│ │ └── test_2_install_x_x.py
│ ├── sec2_sql_command
│ │ ├── __init__.py
│ │ ├── test_1_conn_db_x_x.py
│ │ ├── test_2_import_x_x.py
│ │ ├── test_3_export_x_x.py
│ │ ├── test_4_create_db_x_x.py
│ │ └── test_5_spatial_table_x_x.py
│ ├── sec3_r_tree
│ │ ├── __init__.py
│ │ ├── test_2_rtree_x_x.py
│ │ └── test_3_mbr_x_x.py
│ ├── sec4_access_sqlite_via_python
│ │ ├── __init__.py
│ │ ├── test_1_using_spatialite_in_python_x_x.py
│ │ ├── test_2_import_shapefile_x_x.py
│ │ └── test_3_query_x_x.py
│ ├── sec5_begin_spatialite
│ │ ├── __init__.py
│ │ ├── test_1_select_geometry_x_x.py
│ │ ├── test_2_geometry_x_x.py
│ │ ├── test_3_envelope_x_x.py
│ │ ├── test_4_table_x_x.py
│ │ ├── test_5_transaction_x_x.py
│ │ └── test_6_spatial_ref_x_x.py
│ ├── sec6_other_files
│ │ ├── __init__.py
│ │ ├── test_1_excute_text_x_x.py
│ │ └── test_2_excute_shapefile_x_x.py
│ ├── sec7_spatial_analysis
│ │ ├── __init__.py
│ │ ├── test_1_mbr_relation_x_x.py
│ │ └── test_2_spatial_relation_x_x.py
│ └── test_fig_sqlite_tables_relation.py
├── ch07_mapnik
│ ├── __init__.py
│ ├── sec1_mapnik_intro
│ │ ├── __init__.py
│ │ ├── section_x_x.py
│ │ ├── test_1_intro_x_x.py
│ │ ├── test_3_mapnik_work_x_x.py
│ │ ├── test_4_using_xml_x_x.py
│ │ ├── test_fig_mapnik_how.py
│ │ ├── test_fig_mapnik_varbox.py
│ │ ├── world_population.xml
│ │ └── world_style.xml
│ ├── sec2_mapnik_details
│ │ ├── __init__.py
│ │ ├── test_1_map_and_layer_x_x.py
│ │ ├── test_2_map_attr_x_x.py
│ │ ├── test_3_render_x_x.py
│ │ ├── test_4_format_x_x.py
│ │ └── test_5_proj_x_x.py
│ ├── sec3_datasource
│ │ ├── __init__.py
│ │ ├── test_2_format_x_x.py
│ │ ├── test_3_gdal_ogr_x_x.py
│ │ ├── test_4_PointDatasource_x_x.py
│ │ └── test_fig_mapnik_datasource.py
│ ├── sec4_mapnik_symbols
│ │ ├── __init__.py
│ │ ├── fig_data
│ │ │ ├── __init__.py
│ │ │ └── test_fig_data.py
│ │ ├── sub1_img
│ │ │ ├── __init__.py
│ │ │ └── test_1_image_x_x.py
│ │ ├── sub2_line
│ │ │ ├── __init__.py
│ │ │ ├── test_2_symbol_line_x_x.py
│ │ │ ├── test_fig_line_cap.py
│ │ │ ├── test_fig_line_cap.xml
│ │ │ ├── test_fig_line_dash.py
│ │ │ ├── test_fig_line_dash.xml
│ │ │ ├── test_fig_line_join.py
│ │ │ └── test_fig_line_join.xml
│ │ ├── sub3_poly
│ │ │ ├── __init__.py
│ │ │ ├── test_3_symbol_poly_x_x.py
│ │ │ ├── test_fig_poly_xu.py
│ │ │ └── test_fig_poly_xu.xml
│ │ ├── sub4_label
│ │ │ ├── __init__.py
│ │ │ ├── test_4_symbol_label_x_x.py
│ │ │ ├── test_fig_label_position.py
│ │ │ ├── test_fig_label_position.xml
│ │ │ ├── test_fig_line_label.py
│ │ │ ├── test_fig_line_label.xml
│ │ │ ├── test_fig_symbol_label.py
│ │ │ ├── test_map_label_line.py
│ │ │ ├── test_map_label_line.xml
│ │ │ ├── test_map_label_point.py
│ │ │ ├── test_map_label_point.xml
│ │ │ ├── test_map_label_poly.py
│ │ │ └── test_map_label_poly.xml
│ │ ├── sub5_point
│ │ │ ├── __init__.py
│ │ │ ├── test_5_symbol_point_x_x.py
│ │ │ ├── test_fig_poly_shield.py
│ │ │ ├── test_fig_poly_shield.xml
│ │ │ └── test_sym_file_pt.py
│ │ └── world_map_label_point.xml
│ └── sec5_vector_filter
│ │ ├── __init__.py
│ │ ├── test_1_section_x_x.py
│ │ └── test_2_scale_x_x.py
├── ch08_basemap
│ ├── __init__.py
│ ├── sec1_basic
│ │ ├── __init__.py
│ │ ├── test_1_basic_x_x.py
│ │ ├── test_2_usage_x_x.py
│ │ ├── test_3_projection_x_x.py
│ │ ├── test_4_background_x_x.py
│ │ └── test_5_details_x_x.py
│ ├── sec2_draw
│ │ ├── __init__.py
│ │ ├── test_1_annotate_x_x.py
│ │ ├── test_2_plot_x_x.py
│ │ ├── test_3_text_x_x.py
│ │ └── test_4_labelpoint_x_x.py
│ ├── sec3_with_gis_data
│ │ ├── __init__.py
│ │ ├── test_1_shapefile_x_x.py
│ │ ├── test_2_raster_x_x.py
│ │ └── test_3_legend_scale_x_x.py
│ └── sec4_example
│ │ ├── __init__.py
│ │ ├── test_1_data_x_x.py
│ │ └── test_2_draw_data_x_x.py
├── ch09_others
│ ├── __init__.py
│ ├── sec1_pyshp
│ │ ├── __init__.py
│ │ ├── test_1_pyshp_intro_x_x.py
│ │ ├── test_2_pyshp_reading_x_x.py
│ │ ├── test_3_pyshp_writing_x_x.py
│ │ └── test_4_pyshp_editing_x_x.py
│ ├── sec2_geojson
│ │ ├── __init__.py
│ │ ├── fig_func.py
│ │ ├── test_1_geojson_x_x.py
│ │ ├── test_2_geojson_x_x.py
│ │ └── test_3_geojson_function_x_x.py
│ ├── sec3_descartes
│ │ ├── __init__.py
│ │ ├── test_1_descartes_x_x.py
│ │ ├── test_2_example_x_x.py
│ │ └── test_fig_descartes.py
│ ├── sec4_geopandas
│ │ ├── __init__.py
│ │ ├── section_x_x.py
│ │ ├── test_2_geopandas_frame_x_x.py
│ │ ├── test_3_geopandas_map_x_x.py
│ │ ├── test_4_geopandas_geom_x_x.py
│ │ ├── test_5_geometric_manipulations_x_x.py
│ │ └── test_6_proj_x_x.py
│ └── sec5_folium
│ │ ├── __init__.py
│ │ ├── test_1_basic_x_x.py
│ │ └── test_2_data_x_x.py
├── ch99_append
│ ├── __init__.py
│ └── sec010_the_book
│ │ └── __init__.py
└── figs
│ ├── test_line.py
│ └── test_shapely_buffer.py
├── run_foo.sh
├── run_test.sh
└── run_ts.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | __pycache__
3 | .idea
4 | helper
5 | gdata_bak
6 | gdata
7 | gdata2
8 | .idea/*
9 | .DS_Store
10 | x_*
11 | xx*
12 | *.tex
13 |
14 | pygis.pdf
15 | *.mtc?
16 | *.log
17 | *.aux
18 | *.png
19 | *.jpg
20 | *.pdf
21 |
--------------------------------------------------------------------------------
/ReadMe.rst:
--------------------------------------------------------------------------------
1 | Source codes for book ``Python in open source GIS``
2 | ===========================================================
3 |
4 | Author: [Bu Kun](http://www.osgeo.cn)
5 |
6 | The reposity hosts the source codes for my book ``Python in open source GIS`` (In Chinese language).
7 | The book is being translated into English, which could be found at https://www.gislite.com/catalog/python-gis .
8 |
9 | Installation and Setup
10 | -----------------------------------------
11 | The source code is written and tested under Debian Jessie.
12 | The following tools for libs should be installed first.
13 |
14 | ::
15 |
16 | aptitude install python3-gdal
17 | aptitude install python3-shapely
18 | aptitude install python3-nose
19 |
20 | Build database:
21 |
22 | ::
23 |
24 | ogr2ogr -f SQLite -dsco SPATIALITE=YES xx_china.db /gdata/stats_county.shp -nlt polygon
25 |
26 | 中文说明
27 | ---------------------------------
28 |
29 | 本代码为《Python与开源GIS》一书的脚本。
30 | 书中的大部分内容,发布在网站: (http://www.osgeo.cn/pygis/) 。
31 |
32 | 代码是作为学习使用,提供了作为测试。在学习的时候,最好还是仔细键入运行来查看效果。
33 | 因为代码中用到了一些数据,
34 | 所以需要先行切换到数据目录下使用,免得找不到数据。
35 |
36 |
37 | 使用单元测试 nose
38 | ^^^^^^^^^^^^^^^^^^^^^^^^^
39 |
40 | 首先获取 `helper`
41 |
42 | git clone https://github.com/bukun/tex_helper.git helper
43 |
44 | 单元测试,使用下面命令:
45 |
46 | nosetests3 -v -d --exe part010
47 |
48 | 或者使用(会打印出来信息):
49 |
50 | nosetests3 -v -d -s --exe part010
51 |
52 | 注意
53 | ^^^^^^^^^^^^^^^^^^^^^^^^^
54 |
55 | 为了使 nosetests 能够对代码进行测试运行,文件需要按下面的要求进行组织:
56 |
57 | * 所有的文件夹下面,都得有 `__init__.py` 文件,以使 nosetests 能够正确的遍历到文件夹下。
58 | * 所有的文件,都以`test`开头进行命名。
59 | * 文件的命名,不得含有中文字符、减号、空格、英文句号,及其他奇怪字符;需要进行分隔,可使用下划线`_`。
60 |
61 | Updating notes
62 | ^^^^^^^^^^^^^^^^^^^^^^^^^
63 |
64 | * 20190801: 第三次样稿提交
65 | * 20190416: 第二次校稿更新4
66 | * 20181014: 第二次校稿更新3
67 | * 20181008: 第二次校稿更新2
68 | * 20180922: 第二次校稿更新1
69 | * 20171222: Clean the codes.
70 | * 20170808: The Latex files were merged into the codes.
71 |
--------------------------------------------------------------------------------
/ReadMe_CN.rst:
--------------------------------------------------------------------------------
1 | # 说明
2 |
3 | Author: [Bu Kun](http://www.osgeo.cn)
4 |
5 | 本代码为《Python与开源GIS》一书的脚本。
6 | 书中的大部分内容,发布在网站: [http://www.osgeo.cn/pygis/](http://www.osgeo.cn/pygis/) 。
7 |
8 | 代码是作为学习使用,提供了作为测试。在学习的时候,最好还是仔细键入运行来查看效果。
9 | 因为代码中用到了一些数据,
10 | 所以需要先行切换到数据目录下使用,免得找不到数据。
11 |
12 | ## 安装与配置
13 |
14 | 代码的编写与测试都是在 Debian Jessie下面。需要安装下面的工具:
15 |
16 | aptitude install python3-gdal
17 | aptitude install python3-shapely
18 | aptitude install python3-nose
19 |
20 |
21 | Build database:
22 |
23 | ogr2ogr -f SQLite -dsco SPATIALITE=YES xx_china.db /gdata/stats_county.shp -nlt polygon
24 |
25 |
26 | ## 使用单元测试 nose
27 |
28 | 首先获取 `helper`
29 |
30 | git clone https://github.com/bukun/tex_helper.git helper
31 |
32 | 单元测试,使用下面命令:
33 |
34 | nosetests3 -v -d --exe part010
35 |
36 | 或者使用(会打印出来信息):
37 |
38 | nosetests3 -v -d -s --exe part010
39 |
40 | ## 注意
41 |
42 | 为了使 nosetests 能够对代码进行测试运行,文件需要按下面的要求进行组织:
43 |
44 | * 所有的文件夹下面,都得有 `__init__.py` 文件,以使 nosetests 能够正确的遍历到文件夹下。
45 | * 所有的文件,都以`test`开头进行命名。
46 | * 文件的命名,不得含有中文字符、减号、空格、英文句号,及其他奇怪字符;需要进行分隔,可使用下划线`_`。
47 |
48 | ## Updating notes
49 |
50 | * 20190416: 第二次校稿更新4
51 | * 20181014: 第二次校稿更新3
52 | * 20181008: 第二次校稿更新2
53 | * 20180922: 第二次校稿更新1
54 | * 20171222: Clean the codes.
55 | * 20170808: The Latex files were merged into the codes.
56 |
--------------------------------------------------------------------------------
/debian_install.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | aptitude install -y python3 python3-gdal gdal-bin python3-pyproj proj-bin python3-shapely fiona python3-fiona
4 | aptitude install -y python3-mapnik libspatialite7 libsqlite3-mod-spatialite spatialite-bin
--------------------------------------------------------------------------------
/figures.py:
--------------------------------------------------------------------------------
1 | from math import sqrt
2 | from shapely import affinity
3 |
4 | GM = (sqrt(5)-1.0)/2.0
5 | W = 8.0
6 | H = W*GM
7 | SIZE = (W, H)
8 |
9 | WHITE = '#ffffff'
10 | BLUE = '#6699cc'
11 | GRAY = '#999999'
12 | DARKGRAY = '#333333'
13 | YELLOW = '#ffcc33'
14 | GREEN = '#339933'
15 | RED = '#ff3333'
16 | BLACK = '#000000'
17 |
18 | COLOR_ISVALID = {
19 | True: BLUE,
20 | False: RED,
21 | }
22 |
23 | def plot_line(ax, ob, color=GRAY, zorder=1, linewidth=3, alpha=1):
24 | x, y = ob.xy
25 | ax.plot(x, y, color=color, linewidth=linewidth, solid_capstyle='round', zorder=zorder, alpha=alpha)
26 |
27 | def plot_coords(ax, ob, color=GRAY, zorder=1, alpha=1):
28 | x, y = ob.xy
29 | ax.plot(x, y, 'o', color=color, zorder=zorder, alpha=alpha)
30 |
31 | def color_isvalid(ob, valid=BLUE, invalid=RED):
32 | if ob.is_valid:
33 | return valid
34 | else:
35 | return invalid
36 |
37 | def color_issimple(ob, simple=BLUE, complex=YELLOW):
38 | if ob.is_simple:
39 | return simple
40 | else:
41 | return complex
42 |
43 | def plot_line_isvalid(ax, ob, **kwargs):
44 | kwargs["color"] = color_isvalid(ob)
45 | plot_line(ax, ob, **kwargs)
46 |
47 | def plot_line_issimple(ax, ob, **kwargs):
48 | kwargs["color"] = color_issimple(ob)
49 | plot_line(ax, ob, **kwargs)
50 |
51 | def plot_bounds(ax, ob, zorder=1, alpha=1):
52 | x, y = zip(*list((p.x, p.y) for p in ob.boundary))
53 | ax.plot(x, y, 'o', color=BLACK, zorder=zorder, alpha=alpha)
54 |
55 | def add_origin(ax, geom, origin):
56 | x, y = xy = affinity.interpret_origin(geom, origin, 2)
57 | ax.plot(x, y, 'o', color=GRAY, zorder=1)
58 | ax.annotate(str(xy), xy=xy, ha='center',
59 | textcoords='offset points', xytext=(0, 8))
60 |
61 | def set_limits(ax, x0, xN, y0, yN):
62 | ax.set_xlim(x0, xN)
63 | ax.set_xticks(range(x0, xN+1))
64 | ax.set_ylim(y0, yN)
65 | ax.set_yticks(range(y0, yN+1))
66 | ax.set_aspect("equal")
67 |
--------------------------------------------------------------------------------
/part010/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec1_gis/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec1_gis/test_2_position_distance_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import os
5 | from osgeo import ogr
6 | extfile = 'xx_demo_point.shp'
7 | ###############################################################################
8 | driver = ogr.GetDriverByName("ESRI Shapefile")
9 | if os.access(extfile, os.F_OK):
10 | driver.DeleteDataSource(extfile)
11 | newds = driver.CreateDataSource(extfile)
12 | layernew = newds.CreateLayer('point', None, ogr.wkbPoint)
13 | ###############################################################################
14 | fieldf_x = ogr.FieldDefn("x", ogr.OFTReal)
15 | fieldf_y = ogr.FieldDefn("y", ogr.OFTReal)
16 | layernew.CreateField(fieldf_x)
17 | layernew.CreateField(fieldf_y)
18 | ###############################################################################
19 | point_coors = [[300, 450], [750, 700], [1200, 450],
20 | [750, 200], [750, 450]]
21 | for pt in point_coors:
22 | geom = ogr.CreateGeometryFromWkt(
23 | 'POINT ({0} {1})'.format(pt[0], pt[1]))
24 | feat = ogr.Feature(layernew.GetLayerDefn())
25 | feat.SetField('x', pt[0])
26 | feat.SetField('y', pt[1])
27 | feat.SetGeometry(geom)
28 | layernew.CreateFeature(feat)
29 | newds.Destroy()
30 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec1_gis/test_fig_distance.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from helper.textool import get_tmp_file
4 | import os
5 | from mpl_toolkits.basemap import Basemap
6 |
7 | # import numpy as np
8 | import matplotlib
9 | import matplotlib.pyplot as plt
10 |
11 | matplotlib.use('Agg')
12 |
13 | fig = matplotlib.pyplot.gcf()
14 | fig.set_size_inches(10, 6)
15 |
16 | map = Basemap(projection='merc',
17 | lat_0=0, lon_0=0,
18 | llcrnrlon=-20., llcrnrlat=0., urcrnrlon=180., urcrnrlat=80.)
19 |
20 | # map.drawmapboundary(fill_color='aqua')
21 | map.drawmapboundary(fill_color='white')
22 | # map.fillcontinents(color='coral', lake_color='aqua')
23 | map.fillcontinents(color='#eeeeee', lake_color='#eeeeee')
24 | map.drawcoastlines(color="#999999")
25 |
26 | map.drawparallels(range(0, 90, 20))
27 | map.drawmeridians(range(0, 180, 20))
28 |
29 | # Paris-Tokyo
30 | map.drawgreatcircle(2.3, 48.9, 139.7, 35.6, linewidth=2, color='k')
31 | # Tokyo-Dubai
32 | map.drawgreatcircle(139.7, 35.6, 55.2, 25., linewidth=2, color='k')
33 | # Dubai-Paris
34 | map.drawgreatcircle(55.2, 25., 2.3, 48.9, linewidth=2, color='k')
35 |
36 | # plt.show()
37 |
38 | plt.savefig(get_tmp_file(__file__, '1', file_ext='png'))
39 | plt.savefig(get_tmp_file(__file__, '1', file_ext='pdf'))
40 |
41 | plt.clf()
42 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec1_gis/test_fig_earth.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from helper.textool import get_tmp_file
4 |
5 | import os
6 | from mpl_toolkits.basemap import Basemap
7 | import matplotlib
8 | import matplotlib.pyplot as plt
9 | import numpy as np
10 |
11 | matplotlib.use('Agg')
12 |
13 | fig = matplotlib.pyplot.gcf()
14 | fig.set_size_inches(18.5, 5)
15 |
16 | fig_index = 0
17 |
18 | ######################################################################################################################
19 | '''
20 | 画个图就可以了,分界线是西经20和东经160,这样的两条经线(也就是两条经线所组成的经线圈)把地球分为东西两个半球,
21 | 记住中国在东半球,美国大部分在西半球就可以了。实在不行就在世界地图上用红笔把这两条经线描红,这样总不会错了。
22 | '''
23 |
24 | p1 = plt.subplot(121)
25 | my_map = Basemap(projection='ortho', lat_0=0, lon_0=70, resolution='l', area_thresh=10000.0)
26 | my_map.drawcoastlines()
27 | # my_map.drawcountries()
28 | # my_map.fillcontinents(color='coral')
29 | # my_map.drawmapboundary()
30 | my_map.drawmeridians(np.arange(0, 360, 30))
31 | my_map.drawparallels(np.arange(-90, 90, 30))
32 |
33 | p2 = plt.subplot(122)
34 | my_map2 = Basemap(projection='ortho', lat_0=0, lon_0=-110, resolution='l', area_thresh=10000.0)
35 | my_map2.drawcoastlines()
36 | # my_map2.drawcountries()
37 | # my_map2.fillcontinents(color='coral')
38 | # my_map2.drawmapboundary()
39 | my_map2.drawmeridians(np.arange(0, 360, 30))
40 | my_map2.drawparallels(np.arange(-90, 90, 30))
41 |
42 | # plt.show()
43 |
44 |
45 | plt.savefig(get_tmp_file(__file__, '1', file_ext='png'))
46 | plt.savefig(get_tmp_file(__file__, '1', file_ext='pdf'))
47 |
48 | plt.clf()
49 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec1_gis/test_fig_point_demo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | import mapnik
5 | from helper.textool import get_tmp_file
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | m = mapnik.Map(600, 300)
10 | mapnik.load_map(m, stylesheet)
11 | m.zoom_all()
12 |
13 | lyrs = m.layers
14 | bbox = None
15 | for lyr in lyrs:
16 | bbox = lyr.envelope()
17 |
18 | b2box = mapnik.Box2d(bbox[0], bbox[1] - 10, bbox[2] + 50, bbox[3] + 50)
19 | m.zoom_to_box(b2box)
20 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
21 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
22 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec1_gis/test_fig_point_demo.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec1_gis/test_fig_proj.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from helper.textool import get_tmp_file
4 | import os
5 | import numpy as np
6 | import matplotlib
7 |
8 | from mpl_toolkits.basemap import Basemap
9 | import matplotlib.pyplot as plt
10 |
11 | matplotlib.use('Agg')
12 |
13 | plt.clf()
14 |
15 | fig = matplotlib.pyplot.gcf()
16 | fig.set_size_inches(18.5, 5)
17 |
18 | fig_index = 0
19 |
20 | p1 = plt.subplot(121)
21 | my_map = Basemap()
22 | my_map.drawcoastlines()
23 | my_map.drawmeridians(np.arange(0, 360, 60))
24 | my_map.drawparallels(np.arange(-90, 90, 60))
25 |
26 | p2 = plt.subplot(122)
27 | my_map = Basemap(projection='robin', lat_0=0, lon_0=-100,
28 | resolution='l', area_thresh=1000.0)
29 |
30 | my_map.drawcoastlines()
31 | # my_map.drawcountries()
32 | # my_map.fillcontinents(color='coral')
33 | # my_map.drawmapboundary()
34 |
35 | my_map.drawmeridians(np.arange(0, 360, 60))
36 | my_map.drawparallels(np.arange(-90, 90, 60))
37 |
38 | plt.savefig(get_tmp_file(__file__, '1', file_ext='png'))
39 | plt.savefig(get_tmp_file(__file__, '1', file_ext='pdf'))
40 |
41 | plt.clf()
42 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec2_data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bukun/book_python_gis/cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e/part010/ch01_introduction/sec2_data/__init__.py
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec2_data/test_3_vector_type_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec3_software_install_and_setup/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec3_software_install_and_setup/test_2_install_under_Debian_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec4_python/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec4_python/test_1_intro_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | print('Hello, Python World!')
5 | ###############################################################################
6 | strval1 = 'Welcome '
7 | strval2 = 'Python World!'
8 | strval1 + strval2
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec4_python/test_2_structure_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | n, x, y = 2, 8, 9
5 | ###############################################################################
6 | print("hello world!")
7 | print("hello world!");
8 | ###############################################################################
9 | x=1; y=1 ; z=1
10 | ###############################################################################
11 | sql = "select id,name \
12 | from dept \
13 | where name = 'A'"
14 | sql
15 | ###############################################################################
16 | 4 > 30
17 | True | False
18 | ###############################################################################
19 | int_a = 3
20 | int_b = 4
21 | int_c = 5
22 | ###############################################################################
23 | int_b / int_a
24 | int_b // int_a
25 | ###############################################################################
26 | divmod ( int_c, int_a)
27 | divmod ( int_c * 1.0, int_a)
28 | ###############################################################################
29 | com_i = int_a + int_b * 1j
30 | abs(com_i)
31 | ###############################################################################
32 | 'abcd'
33 | "abcd"
34 | '''abcd'''
35 | 'ab"cd'
36 | "ab'cd"
37 | ###############################################################################
38 | '''a'b"c'd'''
39 | print('''a'b"c'd''')
40 | '''abcd
41 | fdsf'''
42 | print('''abcd
43 | fdsf''')
44 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec4_python/test_3_flow_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | a = 13
5 | b = 50
6 | if a > b:
7 | print('A is greater than B.')
8 | else:
9 | print('B is greater than A.')
10 |
11 | ###############################################################################
12 | rangs = range(1, 3)
13 | for val in rangs:
14 | print(val)
15 | else:
16 | print('The for loop is over')
17 |
18 | ###############################################################################
19 | for i in range(1, 5):
20 | if i > 2:
21 | break
22 | print(i)
23 |
24 | ###############################################################################
25 | for i in range(0, 5):
26 | if i % 2 == 1:
27 | print(i)
28 | else:
29 | continue
30 |
31 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec5_this_book/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch01_introduction/sec5_this_book/test_1_codes_style_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | import matplotlib.pyplot as plt
6 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/chapter_x_x.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | print('=' * 40)
3 | print(__file__)
4 | from helper.textool import get_tmp_file
5 |
6 | ################################################################################
7 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec1_gdal_intro/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec1_gdal_intro/test_2_datamodel_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec2_dataset/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec2_dataset/test_1_using_gdal_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import gdal
5 | ###############################################################################
6 | from osgeo import gdal
7 | ###############################################################################
8 | import gdal
9 | ###############################################################################
10 | try:
11 | import gdal
12 | except:
13 | from osgeo import gdal
14 | ###############################################################################
15 | from osgeo.gdalconst import *
16 | ###############################################################################
17 | gdal.AllRegister()
18 | ###############################################################################
19 | driver = gdal.GetDriverByName('HFA')
20 | driver.Register()
21 | ###############################################################################
22 | driver = gdal.GetDriverByName('GeoTiff')
23 | driver == None
24 | ###############################################################################
25 | drv_count = gdal.GetDriverCount()
26 | drv_count
27 | ###############################################################################
28 | for idx in range(10):
29 | driver = gdal.GetDriver(idx)
30 | print( "%10s: %s" % (driver.ShortName, driver.LongName))
31 |
32 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec2_dataset/test_2_img_info_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | rds = gdal.Open("/gdata/geotiff_file.tif")
6 | ###############################################################################
7 | dir(rds)
8 | ###############################################################################
9 | rds.GetMetadata()
10 | ###############################################################################
11 | ds = gdal.Open('/gdata/lu75c.tif')
12 | ds.GetMetadata()
13 | ###############################################################################
14 | rds.GetDescription()
15 | ###############################################################################
16 | rds.RasterCount
17 | ###############################################################################
18 | mds = gdal.Open("/gdata/MOD09A1.A2009193.h28v06.005.2009203125525.hdf")
19 | mds.RasterCount
20 | ###############################################################################
21 | img_width,img_height=rds.RasterXSize,rds.RasterYSize
22 | img_width,img_height
23 | ###############################################################################
24 | ds.GetGeoTransform()
25 | ###############################################################################
26 | ds.GetProjection()
27 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec2_dataset/test_3_band_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | rds = gdal.Open('/gdata/lu75c.tif')
6 | rds.RasterCount
7 | band = rds.GetRasterBand(1)
8 | ###############################################################################
9 | dir(band)
10 | ###############################################################################
11 | band.XSize
12 | band.YSize
13 | band.DataType
14 | ###############################################################################
15 | band.GetNoDataValue()
16 | band.GetMaximum()
17 | band.GetMinimum()
18 | band.ComputeRasterMinMax()
19 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec3_reading_data/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec3_reading_data/test_1_band_data_type_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdalconst
5 | dir(gdalconst)
6 | ###############################################################################
7 | from osgeo import gdal
8 | rds = gdal.Open("/gdata/geotiff_file.tif")
9 | band = rds.GetRasterBand(1)
10 | band.DataType
11 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec3_reading_data/test_2_access_dataset_data_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | dataset = gdal.Open("/gdata/lu75c.tif")
6 | from numpy import *
7 | dataset.ReadAsArray(2500,2500,3,3)
8 | array([[12, 12, 12],
9 | [12, 12, 12],
10 | [12, 12, 12]],dtype=int16)
11 | dataset.ReadRaster(2500,2500,3,3)
12 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec3_reading_data/test_3_reading_band_data_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | from gdalconst import *
6 | dataset = gdal.Open("/gdata/geotiff_file.tif")
7 | band = dataset.GetRasterBand(1)
8 | band.ReadAsArray(100,100,5,5,10,10)
9 | ###############################################################################
10 | band.XSize
11 | band.YSize
12 | band.ReadAsArray(1496,896,5,5)
13 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec4_create_raster/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec4_create_raster/section_x_x.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | print('=' * 40)
3 | print(__file__)
4 | from helper.textool import get_tmp_file
5 |
6 | ################################################################################
7 | from osgeo import gdal
8 | format = "GTiff"
9 | driver = gdal.GetDriverByName( format )
10 | metadata = driver.GetMetadata()
11 | if gdal.DCAP_CREATE in metadata and metadata[gdal.DCAP_CREATE] == 'YES':
12 | print ('Driver %s supports Create() method.' % format)
13 |
14 |
15 | if gdal.DCAP_CREATECOPY in metadata and metadata[gdal.DCAP_CREATECOPY] == 'YES':
16 | print ('Driver %s supports CreateCopy() method.' % format)
17 |
18 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec4_create_raster/test_1_create_copy_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import gdal
5 | src_filename = "/gdata/geotiff_file.tif"
6 | dst_filename = "/tmp/xx_geotiff_copy.tif"
7 | driver = gdal.GetDriverByName('GTiff')
8 | src_ds = gdal.Open( src_filename )
9 | dst_ds = driver.CreateCopy( dst_filename, src_ds, 0 )
10 | ###############################################################################
11 | dst_filename2 = "/tmp/xx_geotiff_copy2.tif"
12 | dst_ds = driver.CreateCopy( dst_filename2, src_ds, 0,
13 | [ 'TILED=YES', 'COMPRESS=PACKBITS' ] )
14 | dst_filename3 = "/tmp/xx_geotiff_copy3.tif"
15 | dst_ds3 = driver.CreateCopy( dst_filename3, src_ds, 0,
16 | [ 'TILED=NO', 'COMPRESS=PACKBITS' ] )
17 | ###############################################################################
18 | driver.CreateCopy("/tmp/xx_geotiff_copy_a1.tif",src_ds,
19 | 0,["INTERLEAVE=BAND"])
20 | ###############################################################################
21 | driver.CreateCopy("/tmp/xx_geotiff_copy_a2.tif",src_ds,
22 | 0,["INTERLEAVE=PIXEL"])
23 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec4_create_raster/test_2_create_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import gdal
5 | driver = gdal.GetDriverByName( 'GTiff' )
6 | dst_filename = '/tmp/x_tmp.tif'
7 | dst_ds=driver.Create(dst_filename,512,512,1,gdal.GDT_Byte)
8 | ###############################################################################
9 | import numpy, osr
10 | dst_ds.SetGeoTransform([444720, 30, 0, 3751320, 0, -30 ])
11 | srs = osr.SpatialReference()
12 | srs.SetUTM( 11, 1 )
13 | srs.SetWellKnownGeogCS( 'NAD27' )
14 | dst_ds.SetProjection( srs.ExportToWkt() )
15 | raster = numpy.zeros( (512, 512) )
16 | dst_ds.GetRasterBand(1).WriteArray( raster )
17 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec4_create_raster/test_3_create_mul_bands_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | import numpy
6 | dataset = gdal.Open("/gdata/geotiff_file.tif")
7 | width = dataset.RasterXSize
8 | height = dataset.RasterYSize
9 | datas = dataset.ReadAsArray(0,0,width,height)
10 | driver = gdal.GetDriverByName("GTiff")
11 | tods = driver.Create("/tmp/x_geotiff_file_3.tif",width,
12 | height,3,options=["INTERLEAVE=PIXEL"])
13 | tods.WriteRaster(0,0,width,height,datas.tostring(),width,
14 | height,band_list=[1,2,3])
15 | tods.FlushCache()
16 | ###############################################################################
17 | datas = []
18 | for i in range(3):
19 | band = dataset.GetRasterBand(i+1)
20 | data = band.ReadAsArray(0,0,width,height)
21 | datas.append(numpy.reshape(data,(1,-1)))
22 | datas = numpy.concatenate(datas)
23 | ###############################################################################
24 | tods = driver.Create("/tmp/x_geotiff_file_4.tif",width,
25 | height,3,options=["INTERLEAVE=PIXEL"])
26 | tods.WriteRaster(0,0,width,height,datas.tostring(),width,
27 | height,band_list=[1,2,3])
28 | tods.FlushCache()
29 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec4_create_raster/test_4_write_sr_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import osr
5 | import gdal
6 | dataset = gdal.Open("/gdata/geotiff_file.tif")
7 | width = dataset.RasterXSize
8 | height = dataset.RasterYSize
9 | datas = dataset.ReadAsArray(0,0,width,height)
10 | driver = gdal.GetDriverByName("GTiff")
11 | tods = driver.Create("/tmp/x_geotiff_file_3.tif",width,
12 | height,3,options=["INTERLEAVE=PIXEL"])
13 | tods.SetGeoTransform( [ 444720, 30, 0, 3751320, 0, -30 ] )
14 | srs = osr.SpatialReference()
15 | srs.SetUTM( 11, 1 )
16 | srs.SetWellKnownGeogCS( 'NAD27' )
17 | tods.SetProjection( srs.ExportToWkt() )
18 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec4_create_raster/test_5_pyramids_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | gdal.SetConfigOption('HFA_USE_RRD', 'YES')
6 | ###############################################################################
7 | rds = gdal.Open("/gdata/lu75c.tif")
8 | rds.BuildOverviews(overviewlist=[2,4, 8,16,32,64,128])
9 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec5_gdal_others/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec5_gdal_others/test_1_gdal_pillow_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | dataset = gdal.Open("/gdata/geotiff_file.tif")
6 | ###############################################################################
7 | data_arr = dataset.ReadAsArray(30,70,5,5)
8 | type(data_arr)
9 | data_arr
10 | data_bin = dataset.ReadRaster(30,70,5,5)
11 | data_bin
12 | ###############################################################################
13 | data_arr.tostring()
14 | ###############################################################################
15 | from PIL import Image
16 | im = Image.open("/gdata/geotiff_file.tif")
17 | region = im.crop((30,70,35,75))
18 | region.tobytes()
19 | ###############################################################################
20 | import numpy as np
21 | data = dataset.ReadAsArray(30,70,5,5)
22 | from numpy import reshape
23 | datas = [reshape(i,(-1,1)) for i in data]
24 | datas = np.concatenate(datas,1)
25 | datas.tostring()
26 | ###############################################################################
27 | band = dataset.GetRasterBand(1)
28 | band.ReadRaster(30,70,5,5)
29 | ###############################################################################
30 | r,g,b = region.split()
31 | r.tobytes()
32 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec5_gdal_others/test_2_gdal_tools_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 | ###############################################################################
14 | ###############################################################################
15 | ###############################################################################
16 | ###############################################################################
17 | from osgeo import gdal
18 | ds = gdal.Open('/gdata/lu75c.tif')
19 | gdal.Translate('/tmp/xx_output.tif', ds, format = 'GTiff', \
20 | outputSRS ='EPSG:3857', xRes=100, yRes=100)
21 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec5_gdal_others/test_3_index_img_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 |
5 |
6 | ###############################################################################
7 | from osgeo import gdal
8 | dataset = gdal.Open('/gdata/lu75c.tif')
9 | band = dataset.GetRasterBand(1)
10 | band.GetRasterColorInterpretation()
11 | 1
12 | ###############################################################################
13 | from osgeo import gdalconst
14 | dir(gdalconst)
15 | gdalconst.GPI_RGB
16 | gdalconst.GDT_Byte
17 | ###############################################################################
18 | colormap = band.GetRasterColorTable()
19 | colormap is None
20 | ###############################################################################
21 | dataset = gdal.Open('/gdata/lu75i1.tif')
22 | band = dataset.GetRasterBand(1)
23 | band.GetRasterColorInterpretation()
24 | ###############################################################################
25 | gdalconst.GCI_PaletteIndex
26 | ###############################################################################
27 | colormap = band.GetRasterColorTable()
28 | dir(colormap)
29 | colormap.GetCount()
30 | ###############################################################################
31 | gdalconst.GPI_Gray, gdalconst.GPI_RGB, gdalconst.GPI_CMYK, \
32 | gdalconst.GPI_HLS
33 | ###############################################################################
34 | colormap.GetPaletteInterpretation()
35 | gdalconst.GPI_RGB
36 | ###############################################################################
37 | for i in range(colormap.GetCount()):
38 | print("{}:{}".format(i, colormap.GetColorEntry(i)))
39 |
40 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec5_gdal_others/test_4_map_algebra_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | import numpy
6 | dataset = gdal.Open("/gdata/geotiff_file.tif")
7 | band2 = dataset.GetRasterBand(2)
8 | band3 = dataset.GetRasterBand(3)
9 | cols = 100
10 | rows = 100
11 | data2 = band2.ReadAsArray(0, 0,
12 | cols,rows).astype(numpy.float16)
13 | data3 = band3.ReadAsArray(0, 0,
14 | cols,rows).astype(numpy.float16)
15 | ###############################################################################
16 | mask = numpy.greater(data3 + data2, 0)
17 | ###############################################################################
18 | ndvi = numpy.choose(mask,
19 | (-99, (data3 - data2) / (data3 + data2)))
20 | ndvi
21 |
--------------------------------------------------------------------------------
/part010/ch02_gdal/sec5_gdal_others/test_5_affine_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | dataset = gdal.Open("/gdata/geotiff_file.tif")
6 | dataset.GetGCPs()
7 | gtrans = dataset.GetGeoTransform()
8 | gtrans
9 | ###############################################################################
10 | dataset.RasterXSize
11 | dataset.RasterYSize
12 | ###############################################################################
13 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec1_ogr_intro/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec1_ogr_intro/test_1_command_tools_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec2_reading/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec2_reading/test_1_import_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import ogr
5 | ###############################################################################
6 | from osgeo import ogr
7 | ###############################################################################
8 | try:
9 | from osgeo import ogr
10 | except:
11 | import ogr
12 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec2_reading/test_2_datasource_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | inshp = '/gdata/GSHHS_c.shp'
5 | from osgeo import ogr
6 | datasource = ogr.Open(inshp)
7 | driver = datasource.GetDriver()
8 | driver.name
9 | ###############################################################################
10 | dir(datasource)
11 | ###############################################################################
12 | driver = ogr.GetDriverByName('ESRI Shapefile')
13 | ###############################################################################
14 | import sys
15 | datasource = driver.Open(inshp, update=0)
16 | if datasource:
17 | print('done')
18 | else:
19 | print('could not open')
20 | ###############################################################################
21 | drv_count = ogr.GetDriverCount()
22 | drv_count
23 | ###############################################################################
24 | datasource.Destroy()
25 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec2_reading/test_3_layer_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | inshp='/gdata/GSHHS_c.shp'
6 | datasource = ogr.Open(inshp)
7 | layer = datasource.GetLayer(0)
8 | dir(layer)
9 | ###############################################################################
10 | layer.GetFeatureCount()
11 | ###############################################################################
12 | layer.GetExtent()
13 | ###############################################################################
14 | layerdef = layer.GetLayerDefn()
15 | for i in range(layerdef.GetFieldCount()):
16 | defn = layerdef.GetFieldDefn(i)
17 | print(defn.GetName(),defn.GetWidth(),defn.GetType(),
18 | defn.GetPrecision())
19 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec2_reading/test_4_feature_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | inshp ='/gdata/GSHHS_c.shp'
6 | datasource = ogr.Open(inshp)
7 | layer = datasource.GetLayer(0)
8 | feature = layer.GetFeature(0)
9 | ###############################################################################
10 | dir(feature)
11 | ###############################################################################
12 | layer.ResetReading()
13 | feature = layer.GetNextFeature()
14 | while feature:
15 | feature = layer.GetNextFeature()
16 | dir(feature)
17 | ###############################################################################
18 | layer.ResetReading()
19 | feat=layer.GetFeature(0)
20 | feat.keys()
21 | feat.GetField('area')
22 | ###############################################################################
23 | for i in range(feat.GetFieldCount()):
24 | print(feat.GetField(i))
25 |
26 | ###############################################################################
27 | geom = feat.GetGeometryRef()
28 | geom.GetGeometryName()
29 | geom.GetGeometryCount()
30 | geom.GetPointCount()
31 | geom.ExportToWkt()
32 | ###############################################################################
33 | arc0=geom.GetGeometryRef(0)
34 | arc0.GetGeometryName()
35 | arc0.GetGeometryCount()
36 | arc0.GetPointCount()
37 | arc0.GetX(0)
38 | arc0.GetY(0)
39 | arc0.GetZ(0)
40 | arc0.ExportToWkt()
41 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec2_reading/test_5_sr_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | inshp = '/gdata/region_popu.shp'
6 | datasource = ogr.Open(inshp)
7 | layer = datasource.GetLayer(0)
8 | layer.GetSpatialRef()
9 | layer.GetExtent()
10 | ###############################################################################
11 | feature = layer.GetFeature(0)
12 | geom = feature.GetGeometryRef()
13 | geom.GetEnvelope()
14 | ###############################################################################
15 | sr = geom.GetSpatialReference()
16 | dir(sr)
17 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec2_reading/test_fig_ogr_reading.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | '''
4 | 注意,使用的是: `pygraphviz`, 另外,还有 `graphviz`
5 | '''
6 | import os
7 | # from pygraphviz import Digraph
8 |
9 | # from graphviz import Digraph, Graph
10 |
11 | import pygraphviz as pgv
12 |
13 | G = pgv.AGraph(directed=True)
14 | # g = Graph(format='png')
15 | # dot = Digraph()
16 | # dot.format = 'png'
17 | #
18 | #
19 | # dot = Digraph(comment='The Round Table')
20 |
21 | G.add_edge('driver', 'datasource')
22 | G.add_edge('datasource', 'layer')
23 | G.add_edge('layer', 'feature')
24 | G.add_edge('feature', 'geometry')
25 | G.add_edge('geometry', 'wkt')
26 | G.add_edge('shapefile', 'datasource')
27 | G.add_edge('layer', 'layerdef')
28 | G.add_edge('layerdef', 'fieldfn')
29 | G.add_edge('feature', 'field')
30 |
31 | G.layout(prog='dot') # default to neato
32 | outpdf = os.path.join(
33 | os.path.join(
34 | os.path.dirname(__file__),
35 | 'xx{bname}.pdf'.format(
36 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
37 | )))
38 | print(outpdf)
39 | G.draw(outpdf)
40 |
41 | outpng = os.path.join(os.path.join(
42 | os.path.dirname(__file__),
43 | 'xx{bname}.png'.format(bname=os.path.splitext(os.path.basename(__file__))[0][4:])))
44 | G.draw(outpng)
45 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec3_writing/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec3_writing/test_1_Create_Shapefile_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | driver=ogr.GetDriverByName('ESRI Shapefile')
6 | ###############################################################################
7 | ds =driver.CreateDataSource('xx_test.shp')
8 | layer=ds.CreateLayer('test',geom_type=ogr.wkbPoint)
9 | ###############################################################################
10 | fieldDefn = ogr.FieldDefn( 'id',ogr.OFTString)
11 | fieldDefn.SetWidth(4)
12 | layer.CreateField(fieldDefn)
13 | ###############################################################################
14 | featureDefn = layer.GetLayerDefn()
15 | feature = ogr.Feature(featureDefn)
16 | ###############################################################################
17 | point = ogr.Geometry(ogr.wkbPoint)
18 | point.SetPoint(0,123,123)
19 | feature.SetGeometry(point)
20 | ###############################################################################
21 | feature.SetField('id', 23)
22 | ###############################################################################
23 | layer.CreateFeature(feature)
24 | ###############################################################################
25 | ds.Destroy()
26 | ###############################################################################
27 | import os
28 | out_shp = '/tmp/xx_shp_by_ogr.shp'
29 | if os.path.exists(out_shp):
30 | driver.DeleteDataSource(out_shp)
31 | dir(out_shp)
32 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec3_writing/test_4_create_data_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | import os,math
6 | inshp = '/gdata/GSHHS_c.shp'
7 | ds = ogr.Open(inshp)
8 | driver = ogr.GetDriverByName("ESRI Shapefile")
9 | outputfile = '/tmp/xx_GSHHS_copy1.shp'
10 | if os.access( outputfile, os.F_OK ):
11 | driver.DeleteDataSource(outputfile)
12 | ###############################################################################
13 | pt_cp = driver.CopyDataSource(ds, outputfile)
14 | pt_cp.Release()
15 | ###############################################################################
16 | outputfile = '/tmp/xx_GSHHS_copy2.shp'
17 | if os.access(outputfile, os.F_OK):
18 | driver.DeleteDataSource(outputfile)
19 | ###############################################################################
20 | newds = driver.CreateDataSource(outputfile)
21 | layer = ds.GetLayer()
22 | pt_layer = newds.CopyLayer(layer, 'abcd')
23 | newds.Destroy()
24 | ###############################################################################
25 | dir(pt_layer)
26 | ###############################################################################
27 | outputfile ='/tmp/xx_GSHHS_copy3.shp'
28 | if os.access( outputfile, os.F_OK ):
29 | driver.DeleteDataSource( outputfile )
30 | newds = driver.CreateDataSource(outputfile)
31 | layernew = newds.CreateLayer('worldcopy',None,
32 | ogr.wkbLineString)
33 | ###############################################################################
34 | layer = ds.GetLayer()
35 | feature = layer.GetNextFeature()
36 | while feature is not None:
37 | layernew.CreateFeature(feature)
38 | feature = layer.GetNextFeature()
39 | newds.Destroy()
40 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec3_writing/test_5_field_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import os
5 | from osgeo import ogr
6 | driver = ogr.GetDriverByName("ESRI Shapefile")
7 | extfile = '/tmp/rect3.shp'
8 | if os.access( extfile, os.F_OK ):
9 | driver.DeleteDataSource( extfile )
10 | ###############################################################################
11 | newds = driver.CreateDataSource(extfile)
12 | layernew = newds.CreateLayer('rect3',None,ogr.wkbPolygon)
13 | ###############################################################################
14 | field_name = ogr.FieldDefn("name",ogr.OFTString)
15 | field_name.SetWidth(36)
16 | field_area = ogr.FieldDefn("area",ogr.OFTReal)
17 | ###############################################################################
18 | layernew.CreateField(field_name)
19 | layernew.CreateField(field_area)
20 | ###############################################################################
21 | laydef = layernew.GetLayerDefn()
22 | laydef.GetFieldCount()
23 | ###############################################################################
24 | newds.Destroy()
25 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec3_writing/test_6_projection_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | ds = ogr.Open('/gdata/region_popu.shp')
6 | layer = ds.GetLayer(0)
7 | spatialRef = layer.GetSpatialRef()
8 | print(spatialRef)
9 | ...
10 | ###############################################################################
11 | from osgeo import osr
12 | wkt = spatialRef.ExportToWkt()
13 | spatial = osr.SpatialReference()
14 | spatial.ImportFromWkt(wkt)
15 | ###############################################################################
16 | targetSR = osr.SpatialReference()
17 | targetSR.ImportFromEPSG(4326) #Geo WGS84
18 | ###############################################################################
19 | coordTrans = osr.CoordinateTransformation(spatial, targetSR)
20 | ###############################################################################
21 | feature = layer.GetFeature(0)
22 | geom = feature.GetGeometryRef()
23 | geom.ExportToWkt()
24 | ###############################################################################
25 | geom.Transform(coordTrans)
26 | geom.ExportToWkt()
27 | ###############################################################################
28 | targetSR.MorphToESRI()
29 | file = open('/tmp/test.prj', 'w')
30 | file.write(targetSR.ExportToWkt())
31 | file.close()
32 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec4_filter/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec4_filter/help_fig_ogr_filter.py:
--------------------------------------------------------------------------------
1 | ################################################################
2 | from helper.textool import get_tmp_file
3 | import os
4 | import mapnik
5 | from osgeo import ogr
6 |
7 | def create_shp_by_layer(shp, layer):
8 | driver = ogr.GetDriverByName("ESRI Shapefile")
9 | outputfile = shp
10 | if os.access(outputfile, os.F_OK):
11 | driver.DeleteDataSource(outputfile)
12 | newds = driver.CreateDataSource(outputfile)
13 | pt_layer = newds.CopyLayer(layer, '')
14 | newds.Destroy()
15 |
16 | def renderit(shpfile = '', sig=''):
17 | poly_sym = mapnik.PolygonSymbolizer()
18 | poly_sym.fill = mapnik.Color('#f2eff9')
19 | # mapnik.Color('y')
20 | m = mapnik.Map(600, 300, "+proj=latlong +datum=WGS84")
21 | # m.background = mapnik.Color('steelblue')
22 | s = mapnik.Style()
23 | r = mapnik.Rule()
24 | # polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
25 |
26 |
27 | # polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('blue'))
28 | r.symbols.append(poly_sym)
29 | # line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)
30 |
31 |
32 | line_symbolizer = mapnik.LineSymbolizer()
33 | line_symbolizer.stroke = mapnik.Color('#000000')
34 | line_symbolizer.stroke_linecap = mapnik.stroke_linecap.ROUND_CAP
35 | line_symbolizer.stroke_width = 1.2
36 |
37 | # line_symbolizer.stroke_width = 0.1
38 | # line_symbolizer.stroke_dasharray( [5,10])
39 |
40 | r.symbols.append(line_symbolizer)
41 | s.rules.append(r)
42 | m.append_style('My Style', s)
43 | lyr = mapnik.Layer('world', "+proj=latlong +datum=WGS84")
44 | lyr.datasource = mapnik.Shapefile(file=shpfile)
45 | lyr.styles.append('My Style')
46 | m.layers.append(lyr)
47 |
48 | # bbox = mapnik.Box2d(70, 20, 135, 57)
49 |
50 | m.zoom_all()
51 | # mapnik.render_to_file(m, 'xx_world_fk.png', 'png')
52 | mapnik.render_to_file(m, get_tmp_file(__file__, sig))
53 | mapnik.render_to_file(m, get_tmp_file(__file__, sig, file_ext='pdf'), 'pdf')
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec4_filter/test_1_filter_attr_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | import os
6 | shpfile = '/gdata/GSHHS_h.shp'
7 | ds = ogr.Open(shpfile)
8 | layer = ds.GetLayer(0)
9 | layer.GetFeatureCount()
10 | ###############################################################################
11 | layer.SetAttributeFilter("AREA < 1800000")
12 | lyr_count = layer.GetFeatureCount()
13 | print(lyr_count)
14 | ###############################################################################
15 | driver = ogr.GetDriverByName("ESRI Shapefile")
16 | extfile = '/tmp/xx_filter_attr.shp'
17 | if os.access(extfile, os.F_OK):
18 | driver.DeleteDataSource(extfile)
19 |
20 | newds = driver.CreateDataSource(extfile)
21 | lyrn = newds.CreateLayer('rect', None, ogr.wkbPolygon)
22 | ###############################################################################
23 | feat = layer.GetNextFeature()
24 | while feat is not None:
25 | lyrn.CreateFeature(feat)
26 | feat = layer.GetNextFeature()
27 | newds.Destroy()
28 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec4_filter/test_2_filter_spatial_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import os
5 | from osgeo import ogr
6 | def create_shp_by_layer(shp, layer):
7 | outputfile = shp
8 | if os.access(outputfile, os.F_OK):
9 | driver.DeleteDataSource(outputfile)
10 | newds = driver. CreateDataSource ( outputfile )
11 | pt_layer = newds.CopyLayer ( layer, '')
12 | newds.Destroy ()
13 | ###############################################################################
14 | driver = ogr.GetDriverByName("ESRI Shapefile")
15 | world_shp = '/gdata/GSHHS_h.shp'
16 | world_ds = ogr.Open(world_shp)
17 | world_layer = world_ds.GetLayer(0)
18 | ###############################################################################
19 | world_layer.GetFeatureCount()
20 | ###############################################################################
21 | cover_shp = '/gdata/spatial_filter.shp'
22 | cover_ds = ogr.Open(cover_shp)
23 | cover_layer = cover_ds.GetLayer(0)
24 | cover_feats = cover_layer.GetNextFeature()
25 | poly = cover_feats.GetGeometryRef()
26 | ###############################################################################
27 | world_layer.SetSpatialFilter(poly)
28 | ###############################################################################
29 | world_layer.GetFeatureCount()
30 | ###############################################################################
31 | out_shp = '/tmp/world_cover.shp'
32 | create_shp_by_layer(out_shp, world_layer)
33 | ###############################################################################
34 | world_layer.SetSpatialFilter(None)
35 | world_layer.GetFeatureCount()
36 | ###############################################################################
37 | world_layer.SetSpatialFilterRect(-83, 16, -62, 23)
38 | world_layer.GetFeatureCount()
39 | out_shp = '/gdata/world_spatial_filter.shp'
40 | create_shp_by_layer(out_shp, world_layer)
41 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec4_filter/test_3_using_SQL_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import ogr
5 | import os
6 | def create_shp_by_layer(shp, layer):
7 | outputfile = shp
8 | if os.access(outputfile, os.F_OK):
9 | driver.DeleteDataSource(outputfile)
10 | newds = driver. CreateDataSource ( outputfile )
11 | pt_layer = newds.CopyLayer ( layer, '')
12 | newds.Destroy ()
13 | ###############################################################################
14 | driver = ogr.GetDriverByName("ESRI Shapefile")
15 | world_shp = '/gdata/GSHHS_h.shp'
16 | world_ds = ogr.Open(world_shp)
17 | world_layer = world_ds.GetLayer()
18 | world_layer.GetFeatureCount()
19 | ###############################################################################
20 | world_layer_name = world_layer.GetName()
21 | result = world_ds.ExecuteSQL('''
22 | SELECT * FROM {lyr} WHERE AREA > 800000
23 | '''.format(lyr=world_layer_name))
24 | result.GetFeatureCount()
25 | ###############################################################################
26 | resultFeat = result.GetNextFeature ()
27 | out_shp = '/tmp/sql_res.shp'
28 | create_shp_by_layer(out_shp, result)
29 | world_ds.ReleaseResultSet(result)
30 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec4_filter/test_4_application.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | print('=' * 40)
4 | print(__file__)
5 |
6 | from osgeo import ogr
7 | world_shp = '/gdata/GSHHS_c.shp'
8 | world_ds = ogr.Open(world_shp)
9 | ################################################################################
10 | result = world_ds.ExecuteSQL("select * from GSHHS_c")
11 | result.GetFeatureCount()
12 | result = world_ds.ExecuteSQL("select count(*) from GSHHS_c where AREA>50")
13 | result.GetFeatureCount()
14 | ################################################################################
15 | result.GetFeature(0).GetField(0)
16 | ################################################################################
17 | world_ds.ReleaseResultSet(result)
18 | ################################################################################
19 | result = world_ds.ExecuteSQL("select distinct level from GSHHS_c")
20 | resultFeat = result.GetNextFeature()
21 | while resultFeat:
22 | print (resultFeat.GetField(0))
23 | resultFeat = result.GetNextFeature()
24 | world_ds.ReleaseResultSet(result)
25 | ################################################################################
26 | # coverLayer = ds.ExecuteSQL('/gdata/select distinct cover from sites')
27 | #coverFeat = coverLayer.GetNextFeature()
28 |
29 | # while coverFeat:
30 | # cntLayer = ds.ExecuteSQL("select count( * from sites where cover = ‘ “ + coverFeat.GetField(0) + “ ‘ “)
31 | # print (coverFeat.GetField(0) + ' ' +print coverFeat.GetField(0) + ' ' + cntLayer.GetFeature(0).GetFieldAsString(0))
32 | # ds.ReleaseResultSet(cntLayer)
33 | # coverFeat = coverLayer.GetNextFeature()
34 | # ds.ReleaseResultSet(coverLayer)
35 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec4_filter/test_fig_filter_attr.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | 在 test_1 中使用的图
4 | '''
5 | from .help_fig_ogr_filter import renderit, create_shp_by_layer
6 |
7 |
8 | print('=' * 40)
9 | print(__file__)
10 | ################################################################################
11 | from osgeo import ogr
12 | import os
13 |
14 | shpfile = '/gdata/GSHHS_c.shp'
15 | ds = ogr.Open(shpfile)
16 | layer = ds.GetLayer(0)
17 | lyr_count = layer.GetFeatureCount()
18 | print(lyr_count)
19 | ################################################################################
20 | layer.SetAttributeFilter("AREA < 1800000")
21 | lyr_count = layer.GetFeatureCount()
22 | print(lyr_count)
23 | ################################################################################
24 | driver = ogr.GetDriverByName("ESRI Shapefile")
25 | extfile = '/tmp/xx_filter_attr.shp'
26 |
27 | create_shp_by_layer(extfile, layer)
28 |
29 | #
30 | # if os.access(extfile, os.F_OK):
31 | # driver.DeleteDataSource(extfile)
32 | # ################################################################################
33 | # newds = driver.CreateDataSource(extfile)
34 | # layernew = newds.CreateLayer('rect', None, ogr.wkbPolygon)
35 | # feat = layer.GetNextFeature()
36 | # while feat is not None:
37 | # layernew.CreateFeature(feat)
38 | # feat = layer.GetNextFeature()
39 | # newds.Destroy()
40 |
41 | renderit(shpfile=extfile, sig='_attr')
42 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec5_fiona/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec5_fiona/test_1_intro_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec5_fiona/test_2_reading_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import fiona
5 | c = fiona.open('/gdata/GSHHS_c.shp', 'r')
6 | c.closed
7 | ###############################################################################
8 | next(c)
9 | len(c)
10 | ###############################################################################
11 | from pprint import pprint
12 | with fiona.open('/gdata/GSHHS_c.shp') as src:
13 | pprint(src[1])
14 |
15 | ###############################################################################
16 | try:
17 | with fiona.open('/gdata/GSHHS_c.shp') as c:
18 | print(len(list(c)))
19 | except:
20 | print(c.closed)
21 | raise
22 |
23 | ###############################################################################
24 | c = fiona.open('/gdata/GSHHS_c.shp')
25 | c.driver
26 | ###############################################################################
27 | c.crs
28 | ###############################################################################
29 | from fiona.crs import to_string
30 | to_string(c.crs)
31 | ###############################################################################
32 | from fiona.crs import from_string
33 | from_string(
34 | "+datum=WGS84 +ellps=WGS84 +no_defs +proj=longlat")
35 | ###############################################################################
36 | from fiona.crs import from_epsg
37 | from_epsg(3857)
38 | ###############################################################################
39 | len(c)
40 | ###############################################################################
41 | c.bounds
42 |
--------------------------------------------------------------------------------
/part010/ch03_ogr/sec5_fiona/test_3_schema_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from pprint import pprint
5 | import fiona
6 | c = fiona.open('/gdata/GSHHS_c.shp')
7 | pprint(c.schema)
8 | ###############################################################################
9 | rec = next(c)
10 | set(rec.keys()) - set(c.schema.keys())
11 | set(rec['properties'].keys()) == set(
12 | c.schema['properties'].keys())
13 | ###############################################################################
14 | type(rec['properties']['source'])
15 | c.schema['properties']['source']
16 | ###############################################################################
17 | from fiona import prop_width
18 | prop_width('str:25')
19 | prop_width('str')
20 | ###############################################################################
21 | from fiona import prop_type
22 | prop_type('int')
23 | prop_type('float')
24 | prop_type('str:25')
25 | ###############################################################################
26 | c = fiona.open('/gdata/GSHHS_c.shp')
27 | rec = c.next()
28 | pprint(rec)
29 | ###############################################################################
30 | c.close()
31 | rec['id']
32 | ###############################################################################
33 | c = fiona.open('/gdata/GSHHS_c.shp')
34 | rec = next(c)
35 | rec['id']
36 | ###############################################################################
37 | pprint(rec['properties'])
38 | ###############################################################################
39 | pprint(rec['geometry'])
40 |
--------------------------------------------------------------------------------
/part010/ch04_proj/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec1_fundation/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec1_fundation/test_3_concepts_in_proj4_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | from pyproj import Proj
6 | ###############################################################################
7 | import pyproj
8 | pyproj.test()
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 | ###############################################################################
14 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec2_proj_command/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec2_proj_command/test_1_proj_command_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 | ###############################################################################
14 | ###############################################################################
15 | ###############################################################################
16 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec2_proj_command/test_2_proj_setup_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 | ###############################################################################
14 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec2_proj_command/test_3_cs2cs_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec2_proj_command/test_4_geod_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec2_proj_command/test_fig_ls2cc.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from helper.textool import get_tmp_file
4 | import os
5 | from mpl_toolkits.basemap import Basemap
6 |
7 | # import numpy as np
8 | import matplotlib
9 |
10 | matplotlib.rcParams['font.family'] = 'sans-serif'
11 | matplotlib.rcParams['font.sans-serif'] = ['STKaiti']
12 | import matplotlib.pyplot as plt
13 |
14 | fig = matplotlib.pyplot.gcf()
15 | fig.set_size_inches(10, 6)
16 |
17 | # lon = 116.41667
18 | lon1 = 91
19 | # lat = 39.91667
20 | lat1 = 29.6
21 | lon2 = 125.35
22 | lat2 = 43.88333
23 |
24 | para = {
25 | # 'projection': 'geos',
26 | 'lat_0': 0,
27 | 'lon_0': 120,
28 | 'resolution': 'l',
29 | 'area_thresh': 1000.0,
30 | 'llcrnrlon': lon1 - 2,
31 | 'llcrnrlat': lat1 - 2,
32 | 'urcrnrlon': lon2 + 2,
33 | 'urcrnrlat': lat2 + 2
34 | }
35 |
36 | map = Basemap(**para)
37 |
38 | # map.drawmapboundary(fill_color='aqua')
39 | # map.fillcontinents(color='coral', lake_color='aqua')
40 | map.drawcoastlines()
41 |
42 | # map.drawparallels(range(0, 90, 20))
43 | # map.drawmeridians(range(0, 180, 20))
44 |
45 | # Dubai-Paris
46 |
47 | # plt.show()
48 |
49 |
50 | map.drawgreatcircle(lon1, lat1, lon2, lat2, linewidth=1.5, color='k')
51 |
52 | x1, y1 = map(lon1, lat1)
53 | map.plot(x1, y1, 'ko', markersize=6)
54 | plt.text(x1 - 1, y1 -1.2, '拉萨', fontsize=12, fontweight='bold',
55 | ha='left', va='bottom', color='k')
56 |
57 | x2, y2 = map(lon2, lat2)
58 |
59 | map.plot(x2, y2, 'ko', markersize=6)
60 | plt.text(x2 + .3, y2 + .5, '长春', fontsize=12, fontweight='bold',
61 | ha='left', va='center', color='k',
62 | )
63 |
64 | plt.savefig(get_tmp_file(__file__, '1', file_ext='png'), bbox_inches='tight')
65 | plt.savefig(get_tmp_file(__file__, '1', file_ext='pdf'), bbox_inches='tight')
66 |
67 | plt.clf()
68 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec3_pyproj/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec3_pyproj/test_1_Proj_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from pyproj import Proj
5 | p=Proj(
6 | '+proj=aea +lon_0=105 +lat_1=25 +lat_2=47 +ellps=krass')
7 | x,y=p(105,36)
8 | print('%.3f,%.3f' %(x,y))
9 | ###############################################################################
10 | Proj(proj='utm',zone=10,ellps='WGS84')
11 | Proj('+proj=utm +zone=10 +ellps=WGS84')
12 | Proj(init="epsg:32667")
13 | Proj("+init=epsg:32667",preserve_units=True)
14 | ###############################################################################
15 | lon,lat=p(x,y,inverse=True)
16 | print('%.3f,%.3f' %(lon,lat))
17 | ###############################################################################
18 | import math
19 | x,y=p(math.radians(105),math.radians(36),radians=True)
20 | print( '%.3f,%.3f' %(x,y) )
21 | ###############################################################################
22 | lons=(105,106,104)
23 | lats=(36,35,34)
24 | x,y=p(lons,lats)
25 | ###############################################################################
26 | print('%.3f,%.3f,%.3f' %x)
27 | print('%.3f,%.3f,%.3f' %y)
28 | type(x)
29 | ###############################################################################
30 | utm=Proj(proj='utm',zone=48,ellps='WGS84')
31 | ###############################################################################
32 | x,y=utm(105,36)
33 | x,y
34 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec3_pyproj/test_2_transform_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | from pyproj import Proj
6 | albers=Proj(
7 | '+proj=aea +lon_0=105 +lat_1=25 +lat_2=47 +ellps=krass')
8 | albers_x,albers_y=albers(105,36)
9 | albers_x,albers_y
10 | ###############################################################################
11 | utm=Proj(proj='utm',zone=48,ellps='krass')
12 | utm_x,utm_y=utm(105,36)
13 | print(utm_x,utm_y )
14 | ###############################################################################
15 | from pyproj import transform
16 | to_utm_x,to_utm_y = transform(albers,utm,albers_x,albers_y)
17 | print(to_utm_x,to_utm_y )
18 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec3_pyproj/test_3_geod_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from pyproj import Geod
5 | g=Geod(ellps='krass')
6 | ###############################################################################
7 | miniearth=Geod(a=2,b=1.97)
8 | ###############################################################################
9 | ###############################################################################
10 | g.fwd(91, 29.6, 52.88778703659133,3419167.0426993747)
11 | ###############################################################################
12 | ###############################################################################
13 | g.inv(91, 29.6, 125.35, 43.88333)
14 | ###############################################################################
15 | ###############################################################################
16 | g = Geod(ellps='krass')
17 | lasa_lat = 29.6; lasa_lon = 91
18 | cc_lat = 43.88333; cc_lon = 125.35
19 | ###############################################################################
20 | lonlats = g.npts(lasa_lon,lasa_lat,cc_lon,cc_lat,4)
21 | for lon,lat in lonlats: print('%6.3f %7.3f' % (lat, lon))
22 |
23 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec3_pyproj/test_fig_ls2cc_npts.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from helper.textool import get_tmp_file
4 | import os
5 | from mpl_toolkits.basemap import Basemap
6 |
7 | # import numpy as np
8 | import matplotlib
9 |
10 | matplotlib.rcParams['font.family'] = 'sans-serif'
11 | matplotlib.rcParams['font.sans-serif'] = ['STKaiti']
12 | import matplotlib.pyplot as plt
13 |
14 | fig = matplotlib.pyplot.gcf()
15 | fig.set_size_inches(10, 6)
16 |
17 | # lon = 116.41667
18 | lon1 = 91
19 | # lat = 39.91667
20 | lat1 = 29.6
21 | lon2 = 125.35
22 | lat2 = 43.88333
23 |
24 | para = {
25 | # 'projection': 'geos',
26 | 'lat_0': 0,
27 | 'lon_0': 120,
28 | 'resolution': 'l',
29 | 'area_thresh': 1000.0,
30 | 'llcrnrlon': lon1 - 2,
31 | 'llcrnrlat': lat1 - 2,
32 | 'urcrnrlon': lon2 + 2,
33 | 'urcrnrlat': lat2 + 2
34 | }
35 |
36 | map = Basemap(**para)
37 |
38 | # map.drawmapboundary(fill_color='aqua')
39 | # map.fillcontinents(color='coral', lake_color='aqua')
40 | map.drawcoastlines()
41 |
42 | # map.drawparallels(range(0, 90, 20))
43 | # map.drawmeridians(range(0, 180, 20))
44 |
45 | # Dubai-Paris
46 |
47 | # plt.show()
48 |
49 |
50 | map.drawgreatcircle(lon1, lat1, lon2, lat2, linewidth=1.5, color='k')
51 |
52 | x1, y1 = map(lon1, lat1)
53 | map.plot(x1, y1, 'ko', markersize=6)
54 | plt.text(x1 - 1, y1 -1.2, '拉萨', fontsize=12, fontweight='bold',
55 | ha='left', va='bottom', color='k')
56 |
57 | x2, y2 = map(lon2, lat2)
58 |
59 | map.plot(x2, y2, 'ko', markersize=6)
60 | plt.text(x2 + .3, y2 + .5, '长春', fontsize=12, fontweight='bold',
61 | ha='left', va='center', color='k',
62 | )
63 |
64 | npts = [
65 | [33.193, 96.847],
66 | [36.486, 103.170],
67 | [39.415, 110.018],
68 | [41.906, 117.418],
69 | ]
70 |
71 | for npt in npts:
72 | xx, yy = map(npt[1], npt[0])
73 | map.plot(xx, yy, 'kx', markersize=6)
74 |
75 |
76 | plt.savefig(get_tmp_file(__file__, '1', file_ext='png'), bbox_inches='tight')
77 | plt.savefig(get_tmp_file(__file__, '1', file_ext='pdf'), bbox_inches='tight')
78 |
79 | plt.clf()
80 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec4_osr_basic/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec4_osr_basic/test_2_def_geo_coor_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import osr
5 | osrs = osr.SpatialReference()
6 | osrs.SetGeogCS( "My geographic coordinate system",
7 | "WGS_1984",
8 | "My WGS84 Spheroid",
9 | osr.SRS_WGS84_SEMIMAJOR, osr.SRS_WGS84_INVFLATTENING,
10 | "Greenwich", 0.0,
11 | osr.SRS_UA_DEGREE_CONV )
12 | ###############################################################################
13 | osrs.SetWellKnownGeogCS("WGS84")
14 | ###############################################################################
15 | osrs.SetWellKnownGeogCS("EPSG:4326")
16 | ###############################################################################
17 | wkt = osrs.ExportToWkt()
18 | wkt
19 | ###############################################################################
20 | wkt2 = osrs.ExportToPrettyWkt()
21 | print(wkt2)
22 | ###############################################################################
23 | sr = osr.SpatialReference()
24 | sr.SetProjCS( 'UTM 17 (WGS84) in northern hemisphere.' )
25 | wkt = sr.ExportToWkt()
26 | wkt
27 | ###############################################################################
28 | sr.SetWellKnownGeogCS( 'WGS84' )
29 | wkt = sr.ExportToWkt()
30 | wkt
31 | ###############################################################################
32 | sr2 = osr.SpatialReference()
33 | sr2.SetUTM( 17, True )
34 | sr2.SetWellKnownGeogCS( 'WGS84' )
35 | ###############################################################################
36 | wkt2 = sr2.ExportToPrettyWkt()
37 | print(wkt2)
38 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec4_osr_basic/test_3_query_coor_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import osr
5 | sr = osr.SpatialReference()
6 | sr.SetProjCS( 'UTM 17 (WGS84) in northern hemisphere.' )
7 | sr.SetWellKnownGeogCS( 'WGS84' )
8 | sr.SetUTM( 17, True )
9 | sr.IsGeographic()
10 | sr.IsProjected()
11 | ###############################################################################
12 | srs = osr.SpatialReference()
13 | from osgeo import gdal
14 | srs.ImportFromUSGS(8, 0,
15 | (0.0, 0.0,
16 | gdal.DecToPackedDMS(47.0), gdal.DecToPackedDMS(62.0),
17 | gdal.DecToPackedDMS(45.0), gdal.DecToPackedDMS(54.5),
18 | 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
19 | 15)
20 | srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_1)
21 | srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_2)
22 | srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_CENTER)
23 | srs.GetProjParm(osr.SRS_PP_LONGITUDE_OF_CENTER)
24 | srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
25 | srs.GetProjParm(osr.SRS_PP_FALSE_NORTHING)
26 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec4_osr_basic/test_4_sr_from_file_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import gdal
5 | from osgeo import osr
6 | dataset = gdal.Open("/gdata/geotiff_file.tif")
7 | ###############################################################################
8 | sr = dataset.GetProjectionRef()
9 | osrobj = osr.SpatialReference()
10 | osrobj.ImportFromWkt(sr)
11 | ###############################################################################
12 | osrobj.ExportToWkt()
13 | osrobj.MorphToESRI()
14 | ###############################################################################
15 | osrobj.ExportToWkt()
16 | ###############################################################################
17 | osrobj.IsGeographic()
18 | osrobj.IsProjected()
19 | ###############################################################################
20 | dataset2 = gdal.Open("/gdata/lu75c.tif")
21 | sr2 = dataset2.GetProjectionRef()
22 | osrobj2 = osr.SpatialReference()
23 | osrobj2.ImportFromWkt(sr2)
24 | osrobj2.IsSame(osrobj)
25 | ###############################################################################
26 | osrobj3 = osr.SpatialReference()
27 | osrobj3.SetWellKnownGeogCS("WGS84")
28 | osrobj3.IsSame(osrobj2)
29 | osrobj3.IsSame(osrobj)
30 | osrobj3.ExportToWkt()
31 | osrobj3.IsGeographic()
32 | ###############################################################################
33 | from osgeo import ogr, osr
34 | driver = ogr.GetDriverByName('ESRI Shapefile')
35 | dataset = driver.Open('/gdata/GSHHS_c.shp')
36 | layer = dataset.GetLayer()
37 | spatialRef = layer.GetSpatialRef()
38 | ###############################################################################
39 | spatialRef.ExportToWkt()
40 | spatialRef.ExportToPCI()
41 | spatialRef.ExportToUSGS()
42 | spatialRef.ExportToXML()
43 |
--------------------------------------------------------------------------------
/part010/ch04_proj/sec4_osr_basic/test_5_proj_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from osgeo import osr
5 | source = osr.SpatialReference()
6 | source.ImportFromEPSG(2927)
7 | target = osr.SpatialReference()
8 | target.ImportFromEPSG(4326)
9 | transform = osr.CoordinateTransformation(source, target)
10 | transform.TransformPoint(609000,4928000)
11 | ###############################################################################
12 | from osgeo import ogr
13 | point = ogr.CreateGeometryFromWkt(
14 | "POINT (1120351.57 741921.42)")
15 | point.Transform(transform)
16 | point.ExportToWkt()
17 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec1_introduction/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec1_introduction/test_3_quick_start_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import shapely
5 | shapely.__version__
6 | ###############################################################################
7 | import shapely.geos
8 | shapely.geos.geos_version
9 | shapely.geos.geos_capi_version
10 | shapely.geos.geos_version_string
11 | ###############################################################################
12 | from shapely import speedups
13 | speedups.available
14 | ###############################################################################
15 | speedups.disable()
16 | speedups.enable()
17 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec2_geometry_opt/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec2_geometry_opt/test_1_general_funcs_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point
5 | Point(0,0).geom_type
6 | ###############################################################################
7 | Point(0,0).distance(Point(1,1))
8 | ###############################################################################
9 | donut = Point(0, 0).buffer(2.0).difference(
10 | Point(0, 0).buffer(1.0))
11 | donut.centroid.wkt
12 | donut.representative_point().wkt
13 | ###############################################################################
14 | from shapely.geometry import Point
15 | point = Point(10, 10)
16 | pt_buf = point.buffer(5)
17 | pt_buf.wkt
18 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec2_geometry_opt/test_2_simple_geometry_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import LineString
5 | line = LineString([(0, 0), (1, 1)])
6 | line.area
7 | line.length
8 | ###############################################################################
9 | line.bounds
10 | ###############################################################################
11 | len(line.coords)
12 | list(line.coords)
13 | line.coords[1:]
14 | ###############################################################################
15 | line_copy = LineString(line)
16 | ###############################################################################
17 | from shapely.geometry import LinearRing
18 | ring = LinearRing([(0, 0), (1, 1), (1, 0)])
19 | list(ring.coords)
20 | ###############################################################################
21 | from shapely.geometry import Polygon
22 | polygon = Polygon([(0, 0), (1, 1), (1, 0)])
23 | ###############################################################################
24 | list(polygon.interiors)
25 | ###############################################################################
26 | coords = [(0, 0), (1, 1), (1, 0)]
27 | r = LinearRing(coords)
28 | s = Polygon(r)
29 | s.area
30 | ###############################################################################
31 | t = Polygon(s.buffer(1.0).exterior, [r])
32 | t.area
33 | ###############################################################################
34 | from shapely.geometry import box
35 | b = box(0.0, 0.0, 1.0, 1.0)
36 | list(b.exterior.coords)
37 | ###############################################################################
38 | line = LineString()
39 | line.is_empty
40 | line.length
41 | line.bounds
42 | line.coords
43 | ###############################################################################
44 | line.coords = [(0, 0), (1, 1)]
45 | line.is_empty
46 | line.length
47 | line.bounds
48 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec2_geometry_opt/test_3_collects_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import LineString
5 | a = LineString([(0, 0), (1,1), (1,2), (2,2)])
6 | b = LineString([(0, 0), (1,1), (2,1), (2,2)])
7 | c = a.intersection(b)
8 | len(c)
9 | c.wkt
10 | ###############################################################################
11 | for g in c: print(g.wkt)
12 |
13 | for g in c.geoms: print(g.wkt)
14 |
15 | ###############################################################################
16 | c.geoms[0].wkt
17 | c[1].wkt
18 | ###############################################################################
19 | from shapely.geometry import MultiPoint
20 | points = MultiPoint([(0.0, 0.0), (1.0, 1.0)])
21 | points.area
22 | points.length
23 | points.bounds
24 | ###############################################################################
25 | from shapely.geometry import MultiLineString
26 | coords = [((0, 0), (1, 1)), ((-1, 0), (1, 0))]
27 | lines = MultiLineString(coords)
28 | lines.area
29 | lines.length
30 | lines.bounds
31 | len(lines.geoms)
32 | ###############################################################################
33 | polygon = [(0, 0), (1,1), (1,2), (2,2),(0,0)]
34 | s = [(10, 0), (21,1), (31,2), (24,2),(10,0)]
35 | t = [(0, 50), (1,21), (1,22), (32,2),(0,50)]
36 | from shapely.geometry import Polygon
37 | p_a, s_a, t_a = [Polygon(x) for x in [polygon, s, t]]
38 | from shapely.geometry import MultiPolygon
39 | polygons = MultiPolygon([p_a, s_a, t_a])
40 | len(polygons.geoms)
41 | len(polygons)
42 | polygons.bounds
43 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec2_geometry_opt/test_fig_linearring.py:
--------------------------------------------------------------------------------
1 | '''
2 | From shapely respo.
3 | '''
4 |
5 | from matplotlib import pyplot
6 | from shapely.geometry.polygon import LinearRing
7 |
8 | from figures import SIZE, set_limits, plot_coords, plot_line_isvalid
9 |
10 | from matplotlib.font_manager import FontProperties
11 |
12 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
13 |
14 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
15 |
16 | # 1: valid ring
17 | ax = fig.add_subplot(121)
18 | ring = LinearRing([(0, 0), (0, 2), (1, 1), (2, 2), (2, 0), (1, 0.8), (0, 0)])
19 |
20 | plot_coords(ax, ring)
21 | plot_line_isvalid(ax, ring, alpha=0.7)
22 |
23 | ax.set_title('a) 有效', fontproperties=font_song)
24 |
25 | set_limits(ax, -1, 3, -1, 3)
26 |
27 | # 2: invalid self-touching ring
28 | ax = fig.add_subplot(122)
29 | ring2 = LinearRing([(0, 0), (0, 2), (1, 1), (2, 2), (2, 0), (1, 1), (0, 0)])
30 |
31 | plot_coords(ax, ring2)
32 | plot_line_isvalid(ax, ring2, alpha=0.7)
33 |
34 | ax.set_title('b) 无效', fontproperties=font_song)
35 |
36 | set_limits(ax, -1, 3, -1, 3)
37 |
38 | # pyplot.show()
39 |
40 | import os
41 |
42 | plt = pyplot
43 | plt.savefig(os.path.join(
44 | os.path.split(os.path.realpath(__file__))[0],
45 | 'xx{bname}.pdf'.format(
46 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
47 | )), bbox_inches='tight')
48 |
49 | plt.savefig(os.path.join(
50 | os.path.split(os.path.realpath(__file__))[0],
51 | 'xx{bname}.png'.format(
52 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
53 | )), bbox_inches='tight')
54 | pyplot.clf()
55 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec2_geometry_opt/test_fig_multilinestring.py:
--------------------------------------------------------------------------------
1 | '''
2 | From shapely respo.
3 | '''
4 |
5 | from matplotlib import pyplot
6 | from shapely.geometry import MultiLineString
7 |
8 | from matplotlib.font_manager import FontProperties
9 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
10 |
11 | from figures import SIZE, set_limits, plot_line, plot_bounds, color_issimple
12 | from figures import plot_coords as _plot_coords
13 |
14 |
15 | def plot_coords(ax, ob):
16 | for line in ob:
17 | _plot_coords(ax, line, zorder=1)
18 |
19 |
20 | def plot_lines(ax, ob):
21 | color = color_issimple(ob)
22 | for line in ob:
23 | plot_line(ax, line, color=color, alpha=0.7, zorder=2)
24 |
25 |
26 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
27 |
28 | # 1: disconnected multilinestring
29 | ax = fig.add_subplot(121)
30 |
31 | mline1 = MultiLineString([((0, 0), (1, 1)), ((0, 2), (1, 1.5), (1.5, 1), (2, 0))])
32 |
33 | plot_coords(ax, mline1)
34 | plot_bounds(ax, mline1)
35 | plot_lines(ax, mline1)
36 |
37 | ax.set_title('a) 简单线', fontproperties=font_song)
38 |
39 | set_limits(ax, -1, 3, -1, 3)
40 |
41 | # 2: invalid self-touching ring
42 | ax = fig.add_subplot(122)
43 |
44 | mline2 = MultiLineString([((0, 0), (1, 1), (1.5, 1)), ((0, 2), (1, 1.5), (1.5, 1), (2, 0))])
45 |
46 | plot_coords(ax, mline2)
47 | plot_bounds(ax, mline2)
48 | plot_lines(ax, mline2)
49 |
50 | ax.set_title('b) 复合线', fontproperties=font_song)
51 |
52 | set_limits(ax, -1, 3, -1, 3)
53 |
54 | # pyplot.show()
55 |
56 | import os
57 |
58 | plt = pyplot
59 | plt.savefig(os.path.join(
60 | os.path.split(os.path.realpath(__file__))[0],
61 | 'xx{bname}.pdf'.format(
62 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
63 | )), bbox_inches='tight')
64 |
65 | plt.savefig(os.path.join(
66 | os.path.split(os.path.realpath(__file__))[0],
67 | 'xx{bname}.png'.format(
68 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
69 | )), bbox_inches='tight')
70 | pyplot.clf()
71 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec2_geometry_opt/test_fig_multipolygon.py:
--------------------------------------------------------------------------------
1 | from matplotlib import pyplot
2 | from shapely.geometry import MultiPolygon
3 | from descartes.patch import PolygonPatch
4 |
5 | from matplotlib.font_manager import FontProperties
6 |
7 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
8 |
9 | from figures import BLUE, SIZE, set_limits, plot_coords, color_isvalid
10 |
11 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
12 |
13 | # 1: valid multi-polygon
14 | ax = fig.add_subplot(121)
15 |
16 | a = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
17 | b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)]
18 |
19 | multi1 = MultiPolygon([[a, []], [b, []]])
20 |
21 | for polygon in multi1:
22 | plot_coords(ax, polygon.exterior)
23 | patch = PolygonPatch(polygon, facecolor=color_isvalid(multi1), edgecolor=color_isvalid(multi1, valid=BLUE),
24 | alpha=0.5, zorder=2)
25 | ax.add_patch(patch)
26 |
27 | ax.set_title('a) 有效', fontproperties=font_song)
28 |
29 | set_limits(ax, -1, 3, -1, 3)
30 |
31 | # 2: invalid self-touching ring
32 | ax = fig.add_subplot(122)
33 |
34 | c = [(0, 0), (0, 1.5), (1, 1.5), (1, 0), (0, 0)]
35 | d = [(1, 0.5), (1, 2), (2, 2), (2, 0.5), (1, 0.5)]
36 |
37 | multi2 = MultiPolygon([[c, []], [d, []]])
38 |
39 | for polygon in multi2:
40 | plot_coords(ax, polygon.exterior)
41 | patch = PolygonPatch(polygon, facecolor=color_isvalid(multi2), edgecolor=color_isvalid(multi2, valid=BLUE),
42 | alpha=0.5, zorder=2)
43 | ax.add_patch(patch)
44 |
45 | ax.set_title('b) 无效', fontproperties=font_song)
46 |
47 | set_limits(ax, -1, 3, -1, 3)
48 |
49 | # pyplot.show()
50 |
51 | import os
52 |
53 | plt = pyplot
54 | plt.savefig(os.path.join(
55 | os.path.split(os.path.realpath(__file__))[0],
56 | 'xx{bname}.pdf'.format(
57 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
58 | )), bbox_inches='tight')
59 |
60 | plt.savefig(os.path.join(
61 | os.path.split(os.path.realpath(__file__))[0],
62 | 'xx{bname}.png'.format(
63 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
64 | )), bbox_inches='tight')
65 | pyplot.clf()
66 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec3_predicates/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec3_predicates/test_1_one_element_pre_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point
5 | Point(0, 0).has_z
6 | Point(0, 0, 0).has_z
7 | ###############################################################################
8 | from shapely.geometry import LinearRing
9 | LinearRing([(1,0), (1,1), (0,0)]).is_ccw
10 | ###############################################################################
11 | ring = LinearRing([(0,0), (1,1), (1,0)])
12 | ring.is_ccw
13 | ring.coords = list(ring.coords)[::-1]
14 | ring.is_ccw
15 | ###############################################################################
16 | from shapely.geometry import Point
17 | Point().is_empty
18 | Point(0, 0).is_empty
19 | ###############################################################################
20 | from operator import attrgetter
21 | empties = filter(attrgetter('is_empty'),
22 | [Point(), Point(0, 0)])
23 | for g in empties: print(g.wkt)
24 |
25 | ###############################################################################
26 | from shapely.geometry import LineString
27 | LineString([(0, 0), (1, 1), (1, -1)]).is_ring
28 | from shapely.geometry import LinearRing
29 | LinearRing([(0, 0), (1, 1), (1, -1)]).is_ring
30 | ###############################################################################
31 | LineString([(0, 0),(1, 1),(1, -1),(0, 1)]).is_simple
32 | ###############################################################################
33 | from shapely.geometry import MultiPolygon
34 | poly = MultiPolygon([Point(0, 0).buffer(2.0),
35 | Point(1, 1).buffer(2.0)])
36 | poly.is_valid
37 | ###############################################################################
38 | from shapely.validation import explain_validity
39 | explain_validity(poly)
40 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec3_predicates/test_2_tow_elements_pre_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point, LineString
5 | coords = [(0, 0), (1, 1)]
6 | LineString(coords).contains(Point(0.5, 0.5))
7 | Point(0.5, 0.5).within(LineString(coords))
8 | ###############################################################################
9 | LineString(coords).contains(Point(1.0, 1.0))
10 | ###############################################################################
11 | line = LineString(coords)
12 | contained = filter(line.contains, [Point(), Point(0.5, 0.5)])
13 | for g in contained: print(g.wkt)
14 |
15 | ###############################################################################
16 | LineString(coords).crosses(LineString([(0, 1), (1, 0)]))
17 | ###############################################################################
18 | LineString(coords).crosses(Point(0.5, 0.5))
19 | ###############################################################################
20 | Point(0, 0).disjoint(Point(1, 1))
21 | ###############################################################################
22 | a = LineString([(0, 0), (1, 1)])
23 | b = LineString([(0, 0), (0.5, 0.5), (1, 1)])
24 | c = LineString([(0, 0), (0, 0), (1, 1)])
25 | a.equals(b)
26 | b.equals(c)
27 | ###############################################################################
28 | a = LineString([(0, 0), (1, 1)])
29 | b = LineString([(1, 1), (2, 2)])
30 | a.touches(b)
31 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec3_predicates/test_3_de9im_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point
5 | Point(0, 0).relate(Point(1, 1))
6 | ###############################################################################
7 | from shapely.geometry import LineString
8 | Point(0, 0).relate(LineString([(0, 0), (1, 1)]))
9 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec4_spatial_analysis/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec4_spatial_analysis/test_1_sets_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import MultiLineString
5 | coords = [((0, 0), (1, 1)), ((-1, 0), (1, 0))]
6 | lines = MultiLineString(coords)
7 | lines.boundary.wkt
8 | lines.boundary.boundary.wkt
9 | lines.boundary.boundary.is_empty
10 | ###############################################################################
11 | from shapely.geometry import LineString
12 | LineString([(0, 0), (1, 1)]).centroid.wkt
13 | ###############################################################################
14 | from shapely.geometry import Point
15 | a = Point(1, 1).buffer(1.5)
16 | b = Point(2, 1).buffer(1.5)
17 | a.difference(b).wkt
18 | ###############################################################################
19 | a = Point(1, 1).buffer(1.5)
20 | b = Point(2, 1).buffer(1.5)
21 | a.intersection(b).wkt
22 | ###############################################################################
23 | a = Point(1, 1).buffer(1.5)
24 | b = Point(2, 1).buffer(1.5)
25 | a.symmetric_difference(b).wkt
26 | ###############################################################################
27 | a = Point(1, 1).buffer(1.5)
28 | b = Point(2, 1).buffer(1.5)
29 | a.union(b).wkt
30 | ###############################################################################
31 | a.union(b).boundary.wkt
32 | a.boundary.union(b.boundary).wkt
33 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec4_spatial_analysis/test_fig_MBR.py:
--------------------------------------------------------------------------------
1 | from matplotlib import pyplot
2 | from shapely.geometry import MultiPoint
3 |
4 | from descartes.patch import PolygonPatch
5 | from matplotlib.font_manager import FontProperties
6 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
7 | # from pygiser import GRAY, BLUE, set_limits, plot_line
8 | from figures import SIZE, BLUE, GRAY, plot_line, set_limits, DARKGRAY
9 |
10 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
11 | fig.set_frameon(True)
12 |
13 | # 1
14 | ax = fig.add_subplot(121)
15 |
16 | points2 = MultiPoint([(0,1), (2, 1), (3, 1)])
17 | for p in points2:
18 | ax.plot(p.x, p.y, 'o', color=DARKGRAY)
19 | hull2 = points2.convex_hull
20 | plot_line(ax, hull2, color=GRAY, alpha=0.5, zorder=2)
21 |
22 | ax.set_title('a) 点分布在水平线上',fontproperties=font_song)
23 |
24 | set_limits(ax, -1, 4, -1, 3)
25 |
26 | # 2
27 | ax = fig.add_subplot(122)
28 |
29 | points1 = MultiPoint([(1,0), (3, 0.6), (1.5, 2), (0, 1.4)])
30 |
31 | for p in points1:
32 | ax.plot(p.x, p.y, 'o', color=DARKGRAY)
33 | hull1 = points1.envelope
34 |
35 | patch1 = PolygonPatch(hull1, facecolor=GRAY, edgecolor=GRAY, alpha=0.5, zorder=2)
36 | ax.add_patch(patch1)
37 |
38 | ax.set_title('b) 通常情况下的多个点',fontproperties=font_song)
39 |
40 | set_limits(ax, -1, 4, -1, 3)
41 |
42 | # pyplot.show()
43 |
44 | plt = pyplot
45 | import os
46 |
47 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
48 | 'xx{bname}.pdf'.format(
49 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
50 | )
51 | ), bbox_inches='tight')
52 |
53 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
54 | 'xx{bname}.png'.format(
55 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
56 | )
57 | ), bbox_inches='tight')
58 | plt.clf()
59 | plt.close()
60 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec4_spatial_analysis/test_fig_buffer.py:
--------------------------------------------------------------------------------
1 | from matplotlib import pyplot
2 | from shapely.geometry import LineString
3 | from descartes import PolygonPatch
4 |
5 | from matplotlib.font_manager import FontProperties
6 |
7 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
8 |
9 | # from pygiser import BLUE, GRAY, set_limits, plot_line
10 | from figures import SIZE, BLUE, GRAY, plot_line, set_limits, BLACK, DARKGRAY
11 |
12 | line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
13 |
14 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
15 |
16 | # 1
17 | ax = fig.add_subplot(121)
18 |
19 | plot_line(ax, line)
20 |
21 | dilated = line.buffer(0.5, cap_style=3)
22 | patch1 = PolygonPatch(dilated, fc=GRAY, ec=GRAY, alpha=0.5, zorder=2)
23 | ax.add_patch(patch1)
24 |
25 | ax.set_title('a) 膨胀', fontproperties=font_song) # , cap_style=3
26 |
27 | set_limits(ax, -1, 4, -1, 3)
28 |
29 | # 2
30 | ax = fig.add_subplot(122)
31 |
32 | patch2a = PolygonPatch(dilated, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1)
33 | ax.add_patch(patch2a)
34 |
35 | eroded = dilated.buffer(-0.3)
36 |
37 | # GeoJSON-like data works as well
38 |
39 | polygon = eroded.__geo_interface__
40 | # >>> geo['type']
41 | # 'Polygon'
42 | # >>> geo['coordinates'][0][:2]
43 | # ((0.50502525316941682, 0.78786796564403572), (0.5247963548222736, 0.8096820147509064))
44 | patch2b = PolygonPatch(polygon, fc=DARKGRAY, ec=DARKGRAY, alpha=0.5, zorder=2)
45 | ax.add_patch(patch2b)
46 |
47 | ax.set_title('b) 腐蚀', fontproperties=font_song) # join_style=1
48 |
49 | set_limits(ax, -1, 4, -1, 3)
50 |
51 | # pyplot.show()
52 |
53 | plt = pyplot
54 | import os
55 |
56 | plt.savefig(os.path.join(
57 | os.path.split(os.path.realpath(__file__))[0],
58 | 'xx{bname}.pdf'.format(
59 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
60 | )
61 | ), bbox_inches='tight')
62 |
63 | plt.savefig(os.path.join(
64 | os.path.split(os.path.realpath(__file__))[0],
65 | 'xx{bname}.png'.format(
66 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
67 | )
68 | ), bbox_inches='tight')
69 | plt.clf()
70 | plt.close()
71 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec4_spatial_analysis/test_fig_convex_hull.py:
--------------------------------------------------------------------------------
1 | from matplotlib import pyplot
2 | from shapely.geometry import MultiPoint
3 |
4 | from descartes.patch import PolygonPatch
5 | from matplotlib.font_manager import FontProperties
6 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
7 | # from pygiser import GRAY, BLUE, set_limits, plot_line
8 | from figures import SIZE, BLUE, GRAY, plot_line, set_limits, DARKGRAY
9 |
10 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
11 | fig.set_frameon(True)
12 |
13 | # 1
14 | ax = fig.add_subplot(121)
15 |
16 | points2 = MultiPoint([(0, 0), (2, 2)])
17 | for p in points2:
18 | ax.plot(p.x, p.y, 'o', color=DARKGRAY)
19 | hull2 = points2.convex_hull
20 | plot_line(ax, hull2, color=GRAY, alpha=0.5, zorder=2)
21 |
22 | ax.set_title('a) 点的数据为 2时',fontproperties=font_song)
23 |
24 | set_limits(ax, -1, 4, -1, 3)
25 |
26 | # 2
27 | ax = fig.add_subplot(122)
28 |
29 | points1 = MultiPoint([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
30 |
31 | for p in points1:
32 | ax.plot(p.x, p.y, 'o', color=DARKGRAY)
33 | hull1 = points1.convex_hull
34 | patch1 = PolygonPatch(hull1, facecolor=GRAY, edgecolor=GRAY, alpha=0.5, zorder=2)
35 | ax.add_patch(patch1)
36 |
37 | ax.set_title('b) 点的数目大于 2时',fontproperties=font_song)
38 |
39 | set_limits(ax, -1, 4, -1, 3)
40 |
41 | # pyplot.show()
42 |
43 | plt = pyplot
44 | import os
45 |
46 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
47 | 'xx{bname}.pdf'.format(
48 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
49 | )
50 | ), bbox_inches='tight')
51 |
52 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
53 | 'xx{bname}.png'.format(
54 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
55 | )
56 | ), bbox_inches='tight')
57 | plt.clf()
58 | plt.close()
59 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec4_spatial_analysis/test_fig_difference.py:
--------------------------------------------------------------------------------
1 | from matplotlib import pyplot
2 | from shapely.geometry import Point
3 | from descartes import PolygonPatch
4 | from matplotlib.font_manager import FontProperties
5 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
6 | # from pygiser import BLUE, GRAY, set_limits
7 | from figures import SIZE, BLUE, GRAY, DARKGRAY, set_limits
8 |
9 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
10 |
11 | a = Point(1, 1).buffer(1.5)
12 | b = Point(2, 1).buffer(1.5)
13 |
14 | # 1
15 | ax = fig.add_subplot(121)
16 |
17 | patch1 = PolygonPatch(a, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1)
18 | ax.add_patch(patch1)
19 | patch2 = PolygonPatch(b, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1)
20 | ax.add_patch(patch2)
21 | c = a.difference(b)
22 | patchc = PolygonPatch(c, fc=DARKGRAY, ec=DARKGRAY, alpha=0.5, zorder=2)
23 | ax.add_patch(patchc)
24 |
25 | ax.set_title('a.difference(b)')
26 |
27 | set_limits(ax, -1, 4, -1, 3)
28 |
29 | # 2
30 | ax = fig.add_subplot(122)
31 |
32 | patch1 = PolygonPatch(a, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1)
33 | ax.add_patch(patch1)
34 | patch2 = PolygonPatch(b, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1)
35 | ax.add_patch(patch2)
36 | c = b.difference(a)
37 | patchc = PolygonPatch(c, fc=DARKGRAY, ec=DARKGRAY, alpha=0.5, zorder=2)
38 | ax.add_patch(patchc)
39 |
40 | ax.set_title('b.difference(a)')
41 |
42 | set_limits(ax, -1, 4, -1, 3)
43 |
44 | # pyplot.show()
45 |
46 | plt = pyplot
47 | import os
48 |
49 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
50 | 'xx{bname}.pdf'.format(
51 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
52 | )
53 | ), bbox_inches='tight')
54 |
55 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
56 | 'xx{bname}.png'.format(
57 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
58 | )
59 | ), bbox_inches='tight')
60 | plt.clf()
61 | plt.close()
62 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec4_spatial_analysis/test_fig_simplify.py:
--------------------------------------------------------------------------------
1 | from matplotlib import pyplot
2 | from shapely.geometry import MultiPoint, Point
3 | from descartes.patch import PolygonPatch
4 |
5 | # from pygiser import BLUE, GRAY, set_limits
6 | from figures import SIZE, BLUE, GRAY, WHITE,BLACK, set_limits
7 | from matplotlib.font_manager import FontProperties
8 |
9 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
10 |
11 | fig = pyplot.figure(1, figsize=SIZE, dpi=90) # 1, figsize=SIZE, dpi=90)
12 |
13 | p = Point(1, 1).buffer(1.5)
14 |
15 | # 1
16 | ax = fig.add_subplot(121)
17 |
18 | q = p.simplify(0.2)
19 |
20 | patch1a = PolygonPatch(p, facecolor=WHITE, edgecolor=BLACK, alpha=0.5, zorder=1)
21 | ax.add_patch(patch1a)
22 |
23 | patch1b = PolygonPatch(q, facecolor=GRAY, edgecolor=GRAY, alpha=0.5, zorder=2)
24 | ax.add_patch(patch1b)
25 |
26 | ax.set_title('a) 容差值为 0.2', fontproperties=font_song)
27 |
28 | set_limits(ax, -1, 3, -1, 3)
29 |
30 | # 2
31 | ax = fig.add_subplot(122)
32 |
33 | r = p.simplify(0.5)
34 |
35 | patch2a = PolygonPatch(p, facecolor=WHITE, edgecolor=BLACK, alpha=0.5, zorder=1)
36 | ax.add_patch(patch2a)
37 |
38 | patch2b = PolygonPatch(r, facecolor=GRAY, edgecolor=GRAY, alpha=0.5, zorder=2)
39 | ax.add_patch(patch2b)
40 |
41 | ax.set_title('b) 容差值为 0.5', fontproperties=font_song)
42 |
43 | set_limits(ax, -1, 3, -1, 3)
44 |
45 | # pyplot.show()
46 |
47 | plt = pyplot
48 | import os
49 |
50 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
51 | 'xx{bname}.pdf'.format(
52 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
53 | )
54 | ), bbox_inches='tight')
55 |
56 | plt.savefig(os.path.join(os.path.split(os.path.realpath(__file__))[0],
57 | 'xx{bname}.png'.format(
58 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
59 | )
60 | ), bbox_inches='tight')
61 | plt.clf()
62 | plt.close()
63 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec5_operate/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec5_operate/test_1_join_lines_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | lines = [((0, 0), (2, 2)),
5 | ((0, 0), (0, 2)),
6 | ((0, 2), (2, 2)),
7 | ((2, 2), (2, 0)),
8 | ((2, 0), (0, 0))]
9 | ###############################################################################
10 | from shapely.ops import linemerge
11 | the_lines = linemerge(lines)
12 | for aline in the_lines:
13 | print(aline)
14 |
15 | ###############################################################################
16 | from shapely.ops import polygonize
17 | the_polys = polygonize(lines)
18 | for apoly in the_polys:
19 | print(apoly)
20 |
21 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec5_operate/test_2_cascaded_union_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point
5 | from shapely.ops import cascaded_union
6 | polygons = [Point(i, 0).buffer(0.7) for i in range(5)]
7 | ###############################################################################
8 | cascaded_union(polygons).wkt
9 | ###############################################################################
10 | from shapely.geometry import MultiPolygon
11 | m = MultiPolygon(polygons)
12 | m.area
13 | cascaded_union(m).area
14 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec5_operate/test_3_prep_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point
5 | points = [Point(1,1), Point(2,2), Point(1,0)]
6 | ###############################################################################
7 | polygon = Point(1.0, 1.0).buffer(1.0)
8 | from shapely.prepared import prep
9 | prepared_polygon = prep(polygon)
10 | ###############################################################################
11 | hits = filter(prepared_polygon.contains, points)
12 | for x in hits:
13 | print(x.wkt)
14 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec5_operate/test_fig_cascaded_union.py:
--------------------------------------------------------------------------------
1 | '''
2 | From shapely respo.
3 | '''
4 |
5 | from matplotlib import pyplot
6 | from shapely.geometry import Point
7 | from shapely.ops import cascaded_union
8 | from descartes import PolygonPatch
9 |
10 | from matplotlib.font_manager import FontProperties
11 | font_song = FontProperties(fname="/usr/share/fonts/xpfonts/simfang.ttf")
12 |
13 |
14 | from figures import SIZE, BLUE, GRAY, set_limits
15 |
16 | polygons = [Point(i, 0).buffer(0.7) for i in range(5)]
17 |
18 | fig = pyplot.figure(1, figsize=SIZE, dpi=90)
19 |
20 | # 1
21 | ax = fig.add_subplot(121)
22 |
23 | for ob in polygons:
24 | p = PolygonPatch(ob, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1)
25 | ax.add_patch(p)
26 |
27 | ax.set_title('a) 多边形', fontproperties=font_song)
28 |
29 | set_limits(ax, -2, 6, -2, 2)
30 |
31 | # 2
32 | ax = fig.add_subplot(122)
33 |
34 | u = cascaded_union(polygons)
35 | patch2b = PolygonPatch(u, fc=GRAY, ec=GRAY, alpha=0.5, zorder=2)
36 | ax.add_patch(patch2b)
37 |
38 | ax.set_title('b) 合并结果', fontproperties=font_song)
39 |
40 | set_limits(ax, -2, 6, -2, 2)
41 |
42 | # pyplot.show()
43 |
44 | import os
45 |
46 | pyplot.savefig(os.path.join(
47 | os.path.dirname(__file__),
48 | 'xx{bname}.pdf'.format(
49 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
50 | )
51 | ),bbox_inches='tight')
52 |
53 | pyplot.savefig(os.path.join(
54 | os.path.dirname(__file__),
55 | 'xx{bname}.png'.format(
56 | bname=os.path.splitext(os.path.basename(__file__))[0][4:]
57 | )
58 | ),bbox_inches='tight')
59 | pyplot.clf()
60 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec6_interop/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec6_interop/test_1_wkt_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point
5 | Point(0, 0).wkt
6 | Point(0, 0).wkb
7 | ###############################################################################
8 | import codecs
9 | codecs.encode(Point(0, 0).wkb, 'hex_codec')
10 | ###############################################################################
11 | import binascii
12 | binascii.hexlify(Point(0, 0).wkb)
13 | ###############################################################################
14 | from shapely.wkb import dumps, loads
15 | wkb = dumps(Point(0, 0))
16 | loads(wkb).wkt
17 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec6_interop/test_2_numpy_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import Point
5 | from numpy import array
6 | array(Point(0, 0))
7 | from shapely.geometry import LineString
8 | array(LineString([(0, 0), (1, 1)]))
9 | ###############################################################################
10 | Point(0, 0).xy
11 | LineString([(0, 0), (1, 1)]).xy
12 | ###############################################################################
13 | from shapely.geometry import asPoint
14 | pa = asPoint(array([0.0, 0.0]))
15 | pa.wkt
16 | ###############################################################################
17 | from shapely.geometry import asLineString
18 | la = asLineString(array([[1.0, 2.0], [3.0, 4.0]]))
19 | la.wkt
20 |
--------------------------------------------------------------------------------
/part010/ch05_shapely/sec6_interop/test_3_geo_inter_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from shapely.geometry import asShape
5 | d = {"type": "Point", "coordinates": (0.0, 0.0)}
6 | shape = asShape(d)
7 | shape.geom_type
8 | tuple(shape.coords)
9 | list(shape.coords)
10 | ###############################################################################
11 | class GeoThing(object):
12 | def __init__(self, d):
13 | self.__geo_interface__ = d
14 | ###############################################################################
15 | thing = GeoThing(d)
16 | shape = asShape(thing)
17 | shape.geom_type
18 | tuple(shape.coords)
19 | list(shape.coords)
20 | ###############################################################################
21 | from shapely.geometry import mapping
22 | thing = GeoThing(d)
23 | m = mapping(thing)
24 | type(m)
25 | m['type']
26 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec1_concept/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec1_concept/test_2_install_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3
5 | con = sqlite3.connect(":memory:")
6 | con.enable_load_extension(True)
7 | ###############################################################################
8 | ###############################################################################
9 | import sqlite3
10 | con = sqlite3.connect(":memory:")
11 | con.enable_load_extension(True)
12 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
13 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec2_sql_command/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec2_sql_command/test_1_conn_db_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec2_sql_command/test_2_import_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec2_sql_command/test_3_export_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec2_sql_command/test_4_create_db_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec2_sql_command/test_5_spatial_table_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec3_r_tree/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec3_r_tree/test_2_rtree_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 | ###############################################################################
14 | ###############################################################################
15 | ###############################################################################
16 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec3_r_tree/test_3_mbr_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec4_access_sqlite_via_python/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec4_access_sqlite_via_python/test_2_import_shapefile_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | dbfile = 'spalite.db'
6 | con = sqlite.connect(dbfile)
7 | ###############################################################################
8 | con.enable_load_extension(True)
9 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
10 | cursor = con.cursor()
11 | ###############################################################################
12 | cursor.execute("DROP TABLE IF EXISTS pcapital")
13 | cursor.execute('''CREATE TABLE pcapital (id INTEGER PRIMARY
14 | KEY AUTOINCREMENT,name varchar(100))''')
15 | cursor.execute('''CREATE INDEX pcapital_name on
16 | pcapital(name)''')
17 | cursor.execute('''SELECT AddGeometryColumn('pcapital',
18 | 'geom', 4326, 'POINT', 2)''')
19 | cursor.execute("SELECT CreateSpatialIndex('pcapital', 'geom')")
20 | con.commit()
21 | ###############################################################################
22 | from osgeo import ogr
23 | fName = '/gdata/prov_capital.shp'
24 | shapefile = ogr.Open(fName)
25 | layer = shapefile.GetLayer(0)
26 | ###############################################################################
27 | sql_tpl = '''INSERT INTO pcapital (name, geom) VALUES
28 | ('{0}', GeomFromText('{1}', 4326))'''
29 | for i in range(layer.GetFeatureCount()):
30 | feature = layer.GetFeature(i)
31 | fd_name = feature.GetField('name')
32 | geometry = feature.GetGeometryRef()
33 | wkt = geometry.ExportToWkt()
34 | cursor.execute( sql_tpl.format(fd_name ,wkt))
35 | con.commit()
36 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec4_access_sqlite_via_python/test_3_query_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | con = sqlite.connect('spalite.db')
6 | con.enable_load_extension(True)
7 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
8 | cursor = con.cursor()
9 | ###############################################################################
10 | cursor.execute('''SELECT name, AsText(geom)
11 | FROM pcapital WHERE id IN
12 | (SELECT pkid FROM idx_pcapital_geom
13 | WHERE xmin >= 90 AND xmax <= 110
14 | AND ymin >= 30 and ymax<= 40)''')
15 | for row in cursor: print (row)
16 |
17 | ###############################################################################
18 | from shapely.geometry import box
19 | cursor.execute('''SELECT name, AsText(geom) FROM
20 | pcapital WHERE Contains(GeomFromText("{wkt}", 4326), geom)
21 | '''.format(wkt = box(90,30,110,40).wkt))
22 | ###############################################################################
23 | for row in cursor: print (row)
24 |
25 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec5_begin_spatialite/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec5_begin_spatialite/test_1_select_geometry_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | con = sqlite.connect('spalite.db')
6 | con.enable_load_extension(True)
7 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
8 | cursor = con.cursor()
9 | ###############################################################################
10 | sql = 'SELECT name , AsText(Geom) from pcapital limit 5'
11 | cursor.execute(sql)
12 | for rec in cursor: print(rec)
13 |
14 | ###############################################################################
15 | sql ='SELECT name,X(Geom),Y(Geom) FROM pcapital limit 5'
16 | cursor.execute(sql)
17 | for rec in cursor: print(rec)
18 |
19 | ###############################################################################
20 | sql = "SELECT HEX(GeomFromText('POINT(10 20) '));"
21 | cursor.execute(sql)
22 | cursor.fetchone()
23 | ###############################################################################
24 | sql = "SELECT HEX(AsBinary(GeomFromText('POINT (10 20)')))"
25 | cursor.execute(sql)
26 | cursor.fetchone()
27 | ###############################################################################
28 | sql = '''SELECT AsText(GeomFromWKB(
29 | X'010100000000000000000024400000000000003440'))'''
30 | cursor.execute(sql)
31 | cursor.fetchone()
32 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec5_begin_spatialite/test_3_envelope_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | con = sqlite.connect('spalite.db')
6 | con.enable_load_extension(True)
7 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
8 | cursor = con.cursor()
9 | ###############################################################################
10 | sql = '''SELECT Name, AsText(Envelope(Geometry)) FROM
11 | region_popu LIMIT 5'''
12 | cursor.execute(sql)
13 | for x in cursor: print(x)
14 |
15 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec5_begin_spatialite/test_5_transaction_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | con = sqlite.connect('spalite.db')
6 | con.enable_load_extension(True)
7 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
8 | cur = con.cursor()
9 | ###############################################################################
10 | sql_count = 'SELECT count(*) FROM pcapital'
11 | cur.execute(sql_count).fetchone()
12 | ###############################################################################
13 | del_sql = 'DELETE FROM pcapital where id > 10'
14 | cur.execute(del_sql)
15 | cur.execute(sql_count).fetchone()
16 | ###############################################################################
17 | con.rollback()
18 | cur.execute(sql_count).fetchone()
19 | ###############################################################################
20 | cur.execute(del_sql)
21 | con.commit()
22 | ###############################################################################
23 | con.rollback()
24 | cur.execute(sql_count).fetchone()
25 | con.close()
26 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec6_other_files/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec6_other_files/test_1_excute_text_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | cvs_text = '''Author,Book,Lang,Price
5 | "Magnus Lie Hetland","Python基础教程(第3版)","中文","75.3"
6 | "Bill Kropla","Beginning MapServer","English","344"
7 | "Jake VanderPlas","Python数据科学手册","中文","83.9"
8 | "Osvaldo Martin","Python贝叶斯分析","中文","54.4"
9 | '''
10 | ###############################################################################
11 | with open('xx_out.txt', 'w') as fo:
12 | fo.write(cvs_text)
13 | ###############################################################################
14 | import sqlite3 as sqlite
15 | con = sqlite.connect(':memory:')
16 | con.enable_load_extension(True)
17 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
18 | cur = con.cursor()
19 | sql = '''CREATE VIRTUAL TABLE books USING VirtualText(
20 | xx_out.txt, utf8, 1, COMMA, DOUBLEQUOTE, ',')'''
21 | cur.execute(sql)
22 | ###############################################################################
23 | cur.execute('PRAGMA table_info(books)')
24 | for rec in cur: print(rec)
25 |
26 | ###############################################################################
27 | cur.execute('''SELECT Book, Author FROM Books
28 | WHERE Lang = '中文' ''')
29 | for rec in cur: print(rec)
30 |
31 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec6_other_files/test_2_excute_shapefile_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | con = sqlite.connect(":memory:")
6 | con.enable_load_extension(True)
7 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
8 | cur = con.cursor()
9 | ###############################################################################
10 | cur.execute('''CREATE VIRTUAL TABLE vshp USING
11 | VirtualShape("/gdata/prov_capital", "UTF-8", 4326)''')
12 | ###############################################################################
13 | cur.execute('PRAGMA table_info(vshp)')
14 | for rec in cur: print(rec)
15 |
16 | ###############################################################################
17 | cur.execute('''SELECT PKUID, name, lat, lon,
18 | AsText(Geometry) FROM vshp LIMIT 2''')
19 | for rec in cur: print(rec)
20 | ###############################################################################
21 | sql2 = '''SELECT PKUID, name, AsText(Geometry)
22 | FROM vshp WHERE lon > 105 and lat > 35 ORDER BY Name;'''
23 | cur.execute(sql2)
24 | for rec in cur: print(rec)
25 |
26 | ###############################################################################
27 | cur.execute('DROP TABLE vshp')
28 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec7_spatial_analysis/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec7_spatial_analysis/test_1_mbr_relation_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | con = sqlite.connect('spalite.db')
6 | con.enable_load_extension(True)
7 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
8 | cursor = con.cursor()
9 | ###############################################################################
10 | cursor.execute("SELECT count (*) FROM region_popu;")
11 | cursor.fetchone()
12 | ###############################################################################
13 | from shapely.geometry import box
14 | sql = '''SELECT count(*) FROM region_popu WHERE
15 | MBRContains(GeomFromText('{wkt}'), geometry)'''.format(
16 | wkt = box(11265000,3729000,12391000,4488000).wkt)
17 | cursor.execute(sql)
18 | cursor.fetchone()
19 | ###############################################################################
20 | sql = '''SELECT count(*) FROM region_popu WHERE
21 | MBRContains(BuildMBR(11265000,3729000,12391000,4488000),
22 | geometry)'''
23 | cursor.execute(sql)
24 | cursor.fetchone()
25 | ###############################################################################
26 | sql = '''SELECT count (*) FROM region_popu WHERE
27 | MBRContains(BuildCircleMBR (11828000, 4108000, 500000),
28 | geometry)'''
29 | cursor.execute(sql)
30 | cursor.fetchone()
31 | ###############################################################################
32 | sql = '''SELECT count (*) FROM region_popu WHERE
33 | MBRWithin( geometry , BuildMBR(
34 | 11265000,3729000,12391000,4488000))'''
35 | res = cursor.execute(sql)
36 | cursor.fetchone()
37 | ###############################################################################
38 | sql = '''SELECT count (*) FROM region_popu WHERE
39 | MBRIntersects(BuildMBR(11265000,3729000,
40 | 12391000,4488000), geometry)'''
41 | cursor.execute(sql)
42 | cursor.fetchone()
43 |
--------------------------------------------------------------------------------
/part010/ch06_spatialite/sec7_spatial_analysis/test_2_spatial_relation_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import sqlite3 as sqlite
5 | con = sqlite.connect('spalite.db')
6 | con.enable_load_extension(True)
7 | con.execute('SELECT load_extension("mod_spatialite.so.7")')
8 | cursor = con.cursor()
9 | ###############################################################################
10 | cursor.execute('''SELECT DISTINCT Srid(geom3857) FROM
11 | pcapital''')
12 | cursor.fetchone()
13 | cursor.execute('''SELECT DISTINCT Srid(geometry) FROM
14 | region_popu''')
15 | cursor.fetchone()
16 | ###############################################################################
17 | sql = '''SELECT region_popu.Name FROM pcapital,
18 | region_popu WHERE region_popu.Name like '%市%' AND
19 | Within(pcapital.geom3857, region_popu.Geometry) limit 5'''
20 | cursor.execute(sql)
21 | for x in cursor: print(x)
22 |
23 | for x in cursor: print(x)
24 |
25 | ###############################################################################
26 | sql = "select name from region_popu where name like '%市%' "
27 | cursor.execute(sql)
28 | for x in cursor: print(x)
29 |
30 | ...
31 | ###############################################################################
32 | sql = '''SELECT t2.Name,Distance(t1.geom3857,t2.geom3857)
33 | AS Distance FROM pcapital AS t1, pcapital AS t2
34 | WHERE t1.Name = '北京' AND
35 | Distance(t1.geom3857, t2.geom3857) < 400000'''
36 | cursor.execute(sql)
37 | for x in cursor: print(x)
38 |
39 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec1_mapnik_intro/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec1_mapnik_intro/section_x_x.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | print('=' * 40)
3 | print(__file__)
4 | from helper.textool import get_tmp_file
5 |
6 | ################################################################################
7 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec1_mapnik_intro/test_1_intro_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec1_mapnik_intro/test_3_mapnik_work_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | ###############################################################################
6 | m = mapnik.Map(600, 300, "+proj=latlong +datum=WGS84")
7 | m.background = mapnik.Color('steelblue')
8 | mapnik.render_to_file(m, 'xx_background.png', 'png')
9 | ###############################################################################
10 | s = mapnik.Style()
11 | r=mapnik.Rule()
12 | polygon_symbolizer = mapnik.PolygonSymbolizer()
13 | polygon_symbolizer.fill = mapnik.Color('#f2eff9')
14 | r.symbols.append(polygon_symbolizer)
15 | line_symbolizer = mapnik.LineSymbolizer()
16 | line_symbolizer.stroke = mapnik.Color('rgb(50%,50%,50%)')
17 | line_symbolizer.width = 0.1
18 | r.symbols.append(line_symbolizer)
19 | s.rules.append(r)
20 | m.append_style('My Style',s)
21 | ###############################################################################
22 | ds = mapnik.Shapefile(file='/gdata/GSHHS_c.shp')
23 | ###############################################################################
24 | layer = mapnik.Layer('world')
25 | ###############################################################################
26 | layer.datasource = ds
27 | layer.styles.append('My Style')
28 | ###############################################################################
29 | m.layers.append(layer)
30 | m.zoom_all()
31 | ###############################################################################
32 | mapnik.render_to_file(m,'xworld2.png', 'png')
33 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec1_mapnik_intro/test_4_using_xml_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | stylesheet = '/gdata/world_style.xml'
6 | m = mapnik.Map(600, 300)
7 | mapnik.load_map(m, stylesheet)
8 | m.zoom_all()
9 | mapnik.render_to_file(m,'xworld2.png', 'png')
10 | ###############################################################################
11 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec1_mapnik_intro/test_fig_mapnik_how.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | 注意,使用的是: `pygraphviz` , 另外,还有 `graphviz`
4 | '''
5 |
6 | '''
7 | Raw codes in Rest.
8 | .. graphviz::
9 |
10 | digraph G{
11 | Symbol -> Rule [label = "r.symbols.append()", style="dash"];
12 | Rule -> Style [label = "s.rules.append()", style="dash"];
13 | Style -> Map [label = "m.append_style()", style="dash"]
14 | Map -> NamedStyle ;
15 | NamedStyle -> Layer [label = "lyr.styles.append()" ] ;
16 | Layer -> Map [label = "m.layers.append()" ];
17 | Map -> Output [label = "render()" ];
18 | }
19 |
20 | Version, with Mapnik
21 | .. digraph G{
22 | Symbol -> Rule [label = "s.rules.append()", style="dash"];
23 | Rule -> Style [label = "r.styles.append()", style="dash"];
24 | Style -> NamedStyle;
25 | Map -> NamedStyle ;
26 | NamedStyle -> Layer -> Map ;
27 | Map -> Output [label = "render()" ];
28 | Mapnik -> Map ;
29 | Mapnik -> Layer;
30 | Mapnik -> Style ;
31 | Mapnik -> Rule ;
32 | Mapnik -> Symbol ;
33 | }
34 | '''
35 |
36 | import os
37 | # from pygraphviz import Digraph
38 |
39 | # from graphviz import Digraph, Graph
40 | from helper.textool import get_tmp_file
41 | import pygraphviz as pgv
42 |
43 | G = pgv.AGraph(directed=True)
44 | # g = Graph(format='png')
45 | # dot = Digraph()
46 | # dot.format = 'png'
47 | #
48 | #
49 | # dot = Digraph(comment='The Round Table')
50 |
51 | G.add_edge('Symbol', 'Rule', label=" r.symbols.append()", style="dash")
52 | G.add_edge('Rule', 'Style', label=" s.rules.append()", style="dash")
53 | G.add_edge('Style', 'Map', label=" m.append_style()", style="dash")
54 | G.add_edge('Map', 'NamedStyle')
55 | G.add_edge('NamedStyle', 'Layer', label=" lyr.styles.append()")
56 | G.add_edge('Layer', 'Map', label=" m.layers.append()")
57 | G.add_edge('Map', 'Output', label=" render()")
58 |
59 | G.layout(prog='dot') # default to neato
60 | outpng = get_tmp_file(__file__)
61 | G.draw(outpng)
62 |
63 | outpdf = get_tmp_file(__file__, file_ext='pdf')
64 | G.draw(outpdf)
65 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec1_mapnik_intro/world_style.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec2_mapnik_details/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec2_mapnik_details/test_1_map_and_layer_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | nmap = mapnik.Map(600, 400)
6 | ###############################################################################
7 | nmap.srs
8 | ###############################################################################
9 | style1, style2, style3 = [mapnik.Style()] * 3
10 | nmap.append_style("s1", style1)
11 | nmap.append_style("s2", style2)
12 | nmap.append_style("s3", style1)
13 | nmap.append_style("s1", style3)
14 | ###############################################################################
15 | layer = mapnik.Layer('lyrname')
16 | layer.srs
17 | ###############################################################################
18 | ds = mapnik.Shapefile(file='/gdata/GSHHS_c.shp')
19 | layer.datasource = ds
20 | layer.styles.append("s1")
21 | layer.styles.append("s2")
22 | ###############################################################################
23 | nmap.layers.append(layer)
24 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec2_mapnik_details/test_2_map_attr_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | ds = mapnik.Shapefile(file='/gdata/GSHHS_c.shp')
6 | ds.envelope()
7 | ###############################################################################
8 | import os
9 | stylesheet = '/gdata/world_map.xml'
10 | m = mapnik.Map(600, 300)
11 | mapnik.load_map(m, stylesheet)
12 | for x in m.layers:
13 | print(x.name)
14 | print(x.envelope())
15 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec2_mapnik_details/test_3_render_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | import cairo
6 | import os
7 | mapfile = '/gdata/world_population.xml'
8 | projection = '+proj=latlong +datum=WGS84'
9 | m = mapnik.Map(1000, 500)
10 | mapnik.load_map(m, mapfile)
11 | bbox = mapnik.Box2d(-180.0,-90.0,180.0,90.0)
12 | m.zoom_to_box(bbox)
13 | mapnik.render_to_file(m, 'xx_a.png', 'png')
14 | ###############################################################################
15 | surface = cairo.SVGSurface('xx_a.svg', m.width, m.height)
16 | mapnik.render(m, surface)
17 | surface.finish()
18 | ###############################################################################
19 | surface = cairo.PDFSurface('xx_a.pdf', m.width, m.height)
20 | mapnik.render(m, surface)
21 | surface.finish()
22 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec2_mapnik_details/test_4_format_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | mapfile = '/gdata/world_population.xml'
6 | m = mapnik.Map(1000, 500, '+proj=latlong +datum=WGS84')
7 | mapnik.load_map(m, mapfile)
8 | ###############################################################################
9 | m.zoom_all()
10 | mapnik.render_to_file(m, 'map.png')
11 | ###############################################################################
12 | mapnik.render_to_file(map, 'map.png', 'png256')
13 | ###############################################################################
14 | ###############################################################################
15 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec2_mapnik_details/test_5_proj_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | import mapnik
6 | m = mapnik.Map(600, 300, '+init=epsg:4326')
7 | ###############################################################################
8 | lyr = mapnik.Layer('world', "+proj=latlong +datum=WGS84")
9 | lyr.datasource = mapnik.Shapefile(file='/gdata/GSHHS_c.shp')
10 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec3_datasource/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec3_datasource/test_2_format_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | ds = mapnik.Shapefile(file="/gdata/GSHHS_c.shp")
6 | ###############################################################################
7 | ds = mapnik.Shapefile(file="/gdata/GSHHS_c.shp",
8 | encoding="latin1")
9 | ###############################################################################
10 | ds = mapnik.SQLite(file="spalite.db", table="pcapital",
11 | geometry_field="geom", key_field="name")
12 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec3_datasource/test_3_gdal_ogr_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | datasource = mapnik.Gdal(file="/gdata/foo.tif")
6 | ###############################################################################
7 | datasource = mapnik.Ogr(file="/gdata/region_popu.shp",
8 | layer="region_popu")
9 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec3_datasource/test_4_PointDatasource_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import os
5 | import mapnik
6 | stylesheet = '/gdata/world_population.xml'
7 | m = mapnik.Map(600, 300)
8 | mapnik.load_map(m, stylesheet)
9 | m.background = mapnik.Color('steelblue')
10 | s = mapnik.Style()
11 | r = mapnik.Rule()
12 | polygon_symbolizer = mapnik.PolygonSymbolizer()
13 | polygon_symbolizer.fill = mapnik.Color('#f2eff9')
14 | r.symbols.append(polygon_symbolizer)
15 | s.rules.append(r)
16 | m.append_style('My Style2', s)
17 | ###############################################################################
18 | wkt_geom = 'POLYGON ((5 21,-18 -10, -16 -52, 37 -21, 5 21))'
19 | csv_string = '''
20 | wkt,Name
21 | "{wkt_geom}","test"
22 | '''.format(wkt_geom = wkt_geom)
23 | ds = mapnik.Datasource(
24 | **{"type": "csv", "inline": csv_string})
25 | layer2 = mapnik.Layer('world', '+proj=latlong +datum=WGS84')
26 | layer2.datasource = ds
27 | layer2.styles.append('My Style2')
28 | m.layers.append(layer2)
29 | m.zoom_all()
30 | mapnik.render_to_file(m, 'xx_ds_pt.png', 'png')
31 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec3_datasource/test_fig_mapnik_datasource.py:
--------------------------------------------------------------------------------
1 | '''
2 | '''
3 |
4 | import os
5 |
6 | from helper.textool import get_tmp_file
7 | # from pygraphviz import Digraph
8 |
9 | # from graphviz import Digraph, Graph
10 |
11 | import pygraphviz as pgv
12 |
13 | G = pgv.AGraph(directed=True, rankdir="LR", size=[8, 5], concentrate=True)
14 | # g = Graph(format='png')
15 | # dot = Digraph()
16 | # dot.format = 'png'
17 | #
18 | #
19 | # dot = Digraph(comment='The Round Table')
20 |
21 | cfg = {
22 | 'shape': 'box',
23 | 'fixedsize': True,
24 | 'style': 'rounded,filled',
25 | 'width': 2,
26 | 'fontname': 'Arial',
27 | 'fontsize': 10,
28 | 'concentrate': True,
29 | }
30 | # for node_name in ['python3-shapely', 'python3-mapnik', 'python3-pyproj', 'python3-fiona', 'python3-mpltoolkits.basemap',
31 | # 'python3-gdal']:
32 | # G.add_node(node_name, fillcolor="#a0ffa0", **cfg)
33 | #
34 | # cfg['style'] = 'filled'
35 | # for node_name in ['spatialite-bin', 'mapnik-utils', 'proj-bin', 'gdal-bin']:
36 | # G.add_node(node_name, fillcolor="#ffa0a0", **cfg)
37 | #
38 | # for node_name in ['libgdal20', 'libproj12', 'libgeos-c1v5', 'libspatialite7', 'libmapnik3.0']:
39 | # G.add_node(node_name, fillcolor="#eeeeee", **cfg)
40 |
41 | G.add_edge('Mapnik', 'datasource')
42 | G.add_edge('datasource', 'Geospatial Data/Database')
43 |
44 | G.layout(prog='dot') # default to neato
45 | G.draw(get_tmp_file(__file__, '1', file_ext='pdf'))
46 | G.draw(get_tmp_file(__file__, '1', file_ext='png'))
47 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/fig_data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bukun/book_python_gis/cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e/part010/ch07_mapnik/sec4_mapnik_symbols/fig_data/__init__.py
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub1_img/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub1_img/test_1_image_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | m = mapnik.Map(600, 500, "+proj=latlong +datum=WGS84")
6 | symbol = mapnik.RasterSymbolizer()
7 | ###############################################################################
8 | s = mapnik.Style()
9 | r = mapnik.Rule()
10 | r.symbols.append(symbol)
11 | s.rules.append(r)
12 | m.append_style('My Style', s)
13 | datasource = mapnik.Gdal(file='/gdata/geotiff_file.tif')
14 | layer = mapnik.Layer("myLayer")
15 | layer.datasource = datasource
16 | layer.styles.append('My Style')
17 | m.layers.append(layer)
18 | ###############################################################################
19 | layer.envelope()
20 | ###############################################################################
21 | m.zoom_to_box(layer.envelope())
22 | mapnik.render_to_file(m, 'xx_mapnik_result.png', 'png')
23 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub2_line/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bukun/book_python_gis/cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e/part010/ch07_mapnik/sec4_mapnik_symbols/sub2_line/__init__.py
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub2_line/test_fig_line_cap.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import os
4 | import mapnik
5 | from helper.textool import get_tmp_file
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | # image = 'xx_world_style_from_xml.png'
10 | m = mapnik.Map(600, 300)
11 | mapnik.load_map(m, stylesheet)
12 | m.zoom_all()
13 | # m.background = mapnik.Color('steelblue')
14 |
15 | # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
16 | bbox = mapnik.Box2d(-1, -1, 25, 1)
17 | m.zoom_to_box(bbox)
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
20 |
21 |
22 | # stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '1.xml'
23 | #
24 | # # image = 'xx_world_style_from_xml.png'
25 | # m = mapnik.Map(600, 300)
26 | # mapnik.load_map(m, stylesheet)
27 | # m.zoom_all()
28 | # # m.background = mapnik.Color('steelblue')
29 | #
30 | # # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
31 | #
32 | # m.zoom_to_box(bbox)
33 | # mapnik.render_to_file(m, get_tmp_file(__file__, 2), 'png')
34 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub2_line/test_fig_line_dash.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import os
4 | import mapnik
5 | from helper.textool import get_tmp_file
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | # image = 'xx_world_style_from_xml.png'
10 | m = mapnik.Map(600, 300)
11 | mapnik.load_map(m, stylesheet)
12 | m.zoom_all()
13 | # m.background = mapnik.Color('steelblue')
14 |
15 | # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
16 | bbox = mapnik.Box2d(-1, -1, 25, 1)
17 | m.zoom_to_box(bbox)
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
20 |
21 |
22 | # stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '1.xml'
23 | #
24 | # # image = 'xx_world_style_from_xml.png'
25 | # m = mapnik.Map(600, 300)
26 | # mapnik.load_map(m, stylesheet)
27 | # m.zoom_all()
28 | # # m.background = mapnik.Color('steelblue')
29 | #
30 | # # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
31 | #
32 | # m.zoom_to_box(bbox)
33 | # mapnik.render_to_file(m, get_tmp_file(__file__, 2), 'png')
34 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub2_line/test_fig_line_dash.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub2_line/test_fig_line_join.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import os
4 | import mapnik
5 | from helper.textool import get_tmp_file
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | # image = 'xx_world_style_from_xml.png'
10 | m = mapnik.Map(600, 300)
11 | mapnik.load_map(m, stylesheet)
12 | m.zoom_all()
13 | # m.background = mapnik.Color('steelblue')
14 |
15 | # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
16 | bbox = mapnik.Box2d(-1, -1, 25, 1)
17 | m.zoom_to_box(bbox)
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
20 |
21 |
22 | # stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '1.xml'
23 | #
24 | # # image = 'xx_world_style_from_xml.png'
25 | # m = mapnik.Map(600, 300)
26 | # mapnik.load_map(m, stylesheet)
27 | # m.zoom_all()
28 | # # m.background = mapnik.Color('steelblue')
29 | #
30 | # # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
31 | #
32 | # m.zoom_to_box(bbox)
33 | # mapnik.render_to_file(m, get_tmp_file(__file__, 2), 'png')
34 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub3_poly/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bukun/book_python_gis/cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e/part010/ch07_mapnik/sec4_mapnik_symbols/sub3_poly/__init__.py
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub3_poly/test_3_symbol_poly_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mapnik
5 | from gispy_helper import renderit
6 | shpfile = '/gdata/fig_data/fig_data_poly.shp'
7 | symbolizer = mapnik.PolygonSymbolizer()
8 | ###############################################################################
9 | symbolizer.fill = mapnik.Color("steelblue")
10 | linesym = mapnik.LineSymbolizer()
11 | m = renderit(line_sym=linesym, poly_sym=symbolizer,
12 | shpfile = shpfile)
13 | mapnik.render_to_file(m, 'xx_mnik_poly_out.png')
14 | ###############################################################################
15 | symbolizer.fill_opacity = 0.5
16 | m = renderit(line_sym=linesym, poly_sym=symbolizer,
17 | shpfile = shpfile)
18 | mapnik.render_to_file(m, 'xx_mnik_poly_out2.png')
19 | ###############################################################################
20 | linesym.stroke = mapnik.Color('rgb(50%,50%,50%)')
21 | linesym.stroke_linecap = mapnik.stroke_linecap.ROUND_CAP
22 | linesym.stroke_width = 5.0
23 | ###############################################################################
24 | polygon_symbolizer = mapnik.PolygonSymbolizer()
25 | polygon_symbolizer.fill = mapnik.Color('#f2eff9')
26 | ###############################################################################
27 | m = renderit(line_sym=linesym, poly_sym=polygon_symbolizer,
28 | shpfile = shpfile)
29 | mapnik.render_to_file(m, 'xx_mnik_poly_out3.png')
30 | ###############################################################################
31 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub3_poly/test_fig_poly_xu.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import os
4 | import mapnik
5 | from helper.textool import get_tmp_file
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | # image = 'xx_world_style_from_xml.png'
10 | m = mapnik.Map(600, 300)
11 | mapnik.load_map(m, stylesheet)
12 | m.zoom_all()
13 | # m.background = mapnik.Color('steelblue')
14 |
15 |
16 | m.zoom_all()
17 |
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub3_poly/test_fig_poly_xu.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bukun/book_python_gis/cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/__init__.py
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_4_symbol_label_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | ###############################################################################
9 | ###############################################################################
10 | ###############################################################################
11 | ###############################################################################
12 | ###############################################################################
13 | ###############################################################################
14 | import mapnik
15 | for font in mapnik.FontEngine.face_names():
16 | print (font)
17 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_fig_label_position.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | import mapnik
5 | from helper.textool import get_tmp_file
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | # image = 'xx_world_style_from_xml.png'
10 | m = mapnik.Map(600, 150)
11 | mapnik.load_map(m, stylesheet)
12 | m.zoom_all()
13 | # m.background = mapnik.Color('steelblue')
14 |
15 | # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
16 | bbox = mapnik.Box2d(-1, -1, 8, 1)
17 | m.zoom_to_box(bbox)
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
20 |
21 |
22 |
23 |
24 | # stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '1.xml'
25 | #
26 | # # image = 'xx_world_style_from_xml.png'
27 | # m = mapnik.Map(600, 300)
28 | # mapnik.load_map(m, stylesheet)
29 | # m.zoom_all()
30 | # # m.background = mapnik.Color('steelblue')
31 | #
32 | # # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
33 | #
34 | # m.zoom_to_box(bbox)
35 | # mapnik.render_to_file(m, get_tmp_file(__file__, 2), 'png')
36 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_fig_line_label.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import os
4 | import mapnik
5 | from helper.textool import get_tmp_file
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | # image = 'xx_world_style_from_xml.png'
10 | m = mapnik.Map(600, 200)
11 | mapnik.load_map(m, stylesheet)
12 | # m.zoom_all()
13 | # m.background = mapnik.Color('steelblue')
14 |
15 | # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
16 | bbox = mapnik.Box2d(-1,-1,25,1)
17 | m.zoom_to_box(bbox)
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 1,file_ext='pdf'))
20 |
21 |
22 | # stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '1.xml'
23 | #
24 | # # image = 'xx_world_style_from_xml.png'
25 | # m = mapnik.Map(600, 300)
26 | # mapnik.load_map(m, stylesheet)
27 | # m.zoom_all()
28 | # # m.background = mapnik.Color('steelblue')
29 | #
30 | # # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
31 | #
32 | # m.zoom_to_box(bbox)
33 | # mapnik.render_to_file(m, get_tmp_file(__file__, 2), 'png')
34 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_fig_line_label.xml:
--------------------------------------------------------------------------------
1 |
34 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_map_label_line.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import mapnik
4 | from helper.textool import get_tmp_file
5 | import os
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | m = mapnik.Map(600, 200)
10 | mapnik.load_map(m, stylesheet)
11 |
12 |
13 | m.zoom_all()
14 | env = m.envelope()
15 | print(env)
16 | box = mapnik.Box2d(env.minx - .2, env.miny - .2, env.maxx + .1, env.maxy + .2)
17 | m.zoom_to_box(box)
18 |
19 |
20 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
21 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
22 |
23 | for x in m.styles:
24 | for y in x[1].rules:
25 | for z in y.symbols:
26 | tt = z.extract()
27 | print('=' * 20)
28 | print(dir(z.extract()))
29 | try:
30 | print('x' * 60)
31 | print(tt.name())
32 | print('x' * 60)
33 | except:
34 | pass
35 | print('-' * 10)
36 |
37 | print(dir(z.symbol))
38 | print(z.type)
39 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_map_label_line.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_map_label_point.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import mapnik
4 | from helper.textool import get_tmp_file
5 | import os
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | m = mapnik.Map(600, 200)
10 | mapnik.load_map(m, stylesheet)
11 |
12 | m.zoom_all()
13 | env = m.envelope()
14 | print(env)
15 | box = mapnik.Box2d(env.minx - .2, env.miny - .2, env.maxx + .2, env.maxy + .2)
16 | m.zoom_to_box(box)
17 |
18 |
19 |
20 | mapnik.render_to_file(m, get_tmp_file(__file__, 2))
21 | mapnik.render_to_file(m, get_tmp_file(__file__, 2, file_ext='pdf'))
22 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_map_label_point.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_map_label_poly.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import mapnik
4 | from helper.textool import get_tmp_file
5 | import os
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | m = mapnik.Map(600, 200)
10 | mapnik.load_map(m, stylesheet)
11 |
12 | m.zoom_all()
13 | env = m.envelope()
14 | print(env)
15 | box = mapnik.Box2d(env.minx - .3, env.miny - .3, env.maxx + .3, env.maxy + .3)
16 | m.zoom_to_box(box)
17 |
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 3))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 3, file_ext='pdf'))
20 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub4_label/test_map_label_poly.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub5_point/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bukun/book_python_gis/cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e/part010/ch07_mapnik/sec4_mapnik_symbols/sub5_point/__init__.py
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub5_point/test_5_symbol_point_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import os, mapnik
5 | from gispy_helper import renderit
6 | shpfile='/gdata/fig_data/fig_data_poly.shp'
7 | ply_sym = mapnik.PolygonSymbolizer()
8 | ply_sym.fill = mapnik.Color('#f2eff9')
9 | li_sym = mapnik.LineSymbolizer()
10 | pt_sym = mapnik.PointSymbolizer()
11 | m = renderit(point_sym=pt_sym, line_sym=li_sym,
12 | poly_sym=ply_sym,shpfile=shpfile)
13 | m.zoom_all()
14 | mapnik.render_to_file(m, 'xx_point_sym1.png')
15 | ###############################################################################
16 | pt_sym.file = '/gdata/fig_data/turtle.png'
17 | pt_sym.opacity = .8
18 | m = renderit(point_sym=pt_sym, line_sym=li_sym,
19 | poly_sym=ply_sym,shpfile=shpfile)
20 | m.zoom_all()
21 | mapnik.render_to_file(m, 'xx_point_sym2.png')
22 | ###############################################################################
23 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub5_point/test_fig_poly_shield.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import mapnik
4 | from helper.textool import get_tmp_file
5 | import os
6 |
7 | stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'
8 |
9 | m = mapnik.Map(600, 200)
10 | mapnik.load_map(m, stylesheet)
11 |
12 | m.zoom_all()
13 | # env = m.envelope()
14 | # print(env)
15 | # box = mapnik.Box2d(env.minx - .1, env.miny - .3, env.maxx + .3, env.maxy + .3)
16 | # m.zoom_to_box(box)
17 |
18 | mapnik.render_to_file(m, get_tmp_file(__file__, 1))
19 | mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))
20 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub5_point/test_fig_poly_shield.xml:
--------------------------------------------------------------------------------
1 |
19 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/sub5_point/test_sym_file_pt.py:
--------------------------------------------------------------------------------
1 | # # -*- coding: utf-8 -*-
2 | # '''
3 | # 生成绘图的图标
4 | # pip3 install canvasvg
5 | # pip install canvasvg
6 | #
7 | # aptitude install -y python-cairosvg python3-cairosvg
8 | # '''
9 | # from helper.textool import get_tmp_file
10 | # import canvasvg
11 | # import cairosvg
12 | #
13 | # import turtle
14 | #
15 | # turtle.ht()
16 | # turtle.color("purple")
17 | # turtle.pensize(2)
18 | # turtle.goto(4, 8)
19 | # turtle.goto(8, 0)
20 | # turtle.goto(0, 0)
21 | #
22 | # ts = turtle.getscreen()
23 | #
24 | # ts = turtle.getscreen().getcanvas()
25 | #
26 | # tmpfile = 'xx_tmp.svg'
27 | #
28 | # result_png = get_tmp_file(__file__, 't', file_ext='png')
29 | #
30 | # canvasvg.saveall(tmpfile, ts)
31 | # with open(tmpfile) as svg_input, open(result_png, 'wb') as png_output:
32 | # cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
33 | #
34 | #
35 | # # canvasvg.saveall(get_tmp_file(__file__, 't', file_ext='svg'), ts)
36 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec4_mapnik_symbols/world_map_label_point.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec5_vector_filter/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec5_vector_filter/test_1_section_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | import os
7 | import mapnik
8 | m = mapnik.Map(600, 200, "+proj=latlong +datum=WGS84")
9 | m.background = mapnik.Color('#ffffff')
10 | polygon_symbolizer = mapnik.PolygonSymbolizer()
11 | polygon_symbolizer2 = mapnik.PolygonSymbolizer()
12 | polygon_symbolizer.fill = mapnik.Color('#f2eff9')
13 | polygon_symbolizer2.fill = mapnik.Color('#ff0000')
14 | ###############################################################################
15 | r = mapnik.Rule()
16 | r2 = mapnik.Rule()
17 | r.symbols.append(polygon_symbolizer)
18 | r2.symbols.append(polygon_symbolizer2)
19 | r.filter = mapnik.Expression("[id] = 1")
20 | r2.filter = mapnik.Expression("[id] = 2")
21 | ###############################################################################
22 | line_symbolizer = mapnik.LineSymbolizer()
23 | r.symbols.append(line_symbolizer)
24 | r2.symbols.append(line_symbolizer)
25 | ###############################################################################
26 | s = mapnik.Style()
27 | s.rules.append(r)
28 | s.rules.append(r2)
29 | m.append_style('My Style', s)
30 | ###############################################################################
31 | lyr = mapnik.Layer('world', "+proj=latlong +datum=WGS84")
32 | lyr.datasource = mapnik.Shapefile(
33 | file='/gdata/fig_data/fig_data_poly.shp')
34 | lyr.styles.append('My Style')
35 | m.layers.append(lyr)
36 | m.zoom_all()
37 | mapnik.render_to_file(m, 'xx_mapnik_filter.png', 'png')
38 | ###############################################################################
39 | r3 = mapnik.Rule()
40 | r3.set_else(True)
41 | r3.symbols.append(line_symbolizer)
42 | s.rules.append(r3)
43 | m.append_style('My Style2', s)
44 | lyr.styles.append('My Style2')
45 | m.layers.append(lyr)
46 | mapnik.render_to_file(m, 'xx_mapnik_filter.png', 'png')
47 |
--------------------------------------------------------------------------------
/part010/ch07_mapnik/sec5_vector_filter/test_2_scale_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | import mapnik
7 | m = mapnik.Map(600, 400, "+proj=latlong +datum=WGS84")
8 | lyr = mapnik.Layer('world', "+proj=latlong +datum=WGS84")
9 | lyr.datasource = mapnik.Shapefile(file='/gdata/GSHHS_c.shp')
10 | lyr.styles.append('My Style')
11 | m.layers.append(lyr)
12 | m.scale_denominator(), m.scale()
13 | ###############################################################################
14 | bbox = mapnik.Box2d(70, 20, 135, 57)
15 | m.zoom_to_box(bbox)
16 | m.scale_denominator(), m.scale()
17 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec1_basic/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec1_basic/test_1_basic_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec1_basic/test_2_usage_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from mpl_toolkits.basemap import Basemap
5 | import matplotlib.pyplot as plt
6 | ###############################################################################
7 | bsmap = Basemap()
8 | ###############################################################################
9 | bsmap.drawcoastlines()
10 | plt.show()
11 | ###############################################################################
12 | plt.savefig('xx_test.png')
13 | ###############################################################################
14 | bsmap = Basemap(projection='ortho',lat_0=0, lon_0=105)
15 | bsmap.drawmapboundary(fill_color='aqua')
16 | ###############################################################################
17 | bsmap.fillcontinents(color= 'coral',lake_color='aqua')
18 | bsmap.drawcoastlines()
19 | plt.show()
20 | ###############################################################################
21 | plt.cla() # Clear axis
22 | plt.clf() # Clear figure
23 | plt.close() # Close a figure window
24 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec1_basic/test_3_projection_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import mpl_toolkits.basemap
5 | print(mpl_toolkits.basemap.supported_projections)
6 | ###############################################################################
7 | from mpl_toolkits.basemap import Basemap
8 | import matplotlib.pyplot as plt
9 | import numpy as np
10 | bsmap = Basemap(projection='cyl')
11 | bsmap.drawcoastlines()
12 | bsmap.drawmeridians(np.arange(0, 360, 30))
13 | bsmap.drawparallels(np.arange(-90, 90, 30))
14 | plt.show()
15 | ###############################################################################
16 | bsmap = Basemap(projection='aeqd', lon_0=180, lat_0=50)
17 | bsmap.drawmapboundary()
18 | bsmap.drawcoastlines()
19 | plt.show()
20 | ###############################################################################
21 | bsmap = Basemap(projection='mbtfpq', lon_0=105)
22 | bsmap.drawcoastlines()
23 | bsmap.drawmeridians(np.arange(0, 360, 30))
24 | bsmap.drawparallels(np.arange(-90, 90, 30))
25 | plt.show()
26 | ###############################################################################
27 | ###############################################################################
28 | from mpl_toolkits.basemap import Basemap
29 | import matplotlib.pyplot as plt
30 | bsmap = Basemap(projection='aeqd', lon_0 = 10, lat_0 = 50)
31 | bsmap(10,50)
32 | ###############################################################################
33 | bsmap(20015077.3712, 20015077.3712, inverse=True)
34 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec1_basic/test_4_background_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from mpl_toolkits.basemap import Basemap
5 | import matplotlib.pyplot as plt
6 | plt.subplot(121)
7 | bsmap = Basemap(projection='ortho',lon_0=0,
8 | lat_0=0,resolution='c')
9 | bsmap.drawmapboundary()
10 | plt.subplot(122)
11 | bsmap = Basemap(projection='sinu',lon_0=0,resolution='c')
12 | bsmap.drawmapboundary(fill_color='aqua')
13 | plt.show()
14 | ###############################################################################
15 | bsmap = Basemap(projection='poly',
16 | lon_0=0.0, lat_0=0, llcrnrlon=-80.,
17 | llcrnrlat=-40,urcrnrlon=80.,urcrnrlat=40.)
18 | bsmap.drawmapboundary()
19 | bsmap.drawcoastlines()
20 | ###############################################################################
21 | bsmap.drawmeridians(range(0, 360, 20))
22 | ###############################################################################
23 | bsmap.drawparallels(range(-90, 100, 10), linewidth=2,
24 | dashes=[4, 2], labels=[1,0,0,1], color='r' )
25 | plt.show()
26 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec1_basic/test_5_details_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | import os
6 | from mpl_toolkits.basemap import Basemap
7 | import matplotlib.pyplot as plt
8 | import numpy as np
9 | para = {
10 | 'projection': 'merc', 'lat_0': 0, 'lon_0': 120,
11 | 'resolution': 'l', 'area_thresh': 1000.0,
12 | 'llcrnrlon': 116, 'llcrnrlat': 36.6,
13 | 'urcrnrlon': 124, 'urcrnrlat': 40.2 }
14 | ###############################################################################
15 | my_map = Basemap(**para)
16 | my_map.drawcoastlines()
17 | plt.show()
18 | ###############################################################################
19 | para['resolution'] = 'h'
20 | my_map = Basemap(**para)
21 | my_map.drawcoastlines()
22 | plt.show()
23 | ###############################################################################
24 | para['area_thresh'] = .1
25 | my_map = Basemap(**para)
26 | my_map.drawcoastlines()
27 | plt.show()
28 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec2_draw/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec2_draw/test_1_annotate_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import matplotlib
5 | matplotlib.rcParams['font.family'] = 'sans-serif'
6 | matplotlib.rcParams['font.sans-serif'] = ['STKaiti']
7 | ###############################################################################
8 | from mpl_toolkits.basemap import Basemap
9 | import matplotlib.pyplot as plt
10 | import numpy as np
11 | fig = plt.figure(figsize=(6, 4))
12 | plt.subplots_adjust(left=0.05, right=0.95, top=0.90,
13 | bottom=0.05, wspace=0.15, hspace=0.05)
14 | m = Basemap(resolution='i',projection='merc',llcrnrlat=10.0,
15 | urcrnrlat=55.0, llcrnrlon=60., urcrnrlon=140.0)
16 | m.drawcoastlines(linewidth=0.5)
17 | m.drawparallels(np.arange(10., 55., 10.),labels=[1,0,0,0],
18 | linewidth=0.2, dashes=[4,2])
19 | m.drawmeridians(np.arange(60., 140., 10.),labels=[0,0,0,1],
20 | linewidth=0.2, dashes=[4,2])
21 | ###############################################################################
22 | x, y = m(116.42, 40.21)
23 | x2, y2 = m(125.27, 43.83)
24 | plt.annotate('北京', xy=(x, y), xycoords='data',
25 | xytext=(x2, y2), textcoords='data', color='r',
26 | arrowprops=dict(arrowstyle="fancy", color='g') )
27 | plt.show()
28 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec2_draw/test_2_plot_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from mpl_toolkits.basemap import Basemap
5 | import matplotlib.pyplot as plt
6 | para = {'projection': 'merc', 'lat_0': 0, 'lon_0': 120,
7 | 'resolution': 'h', 'area_thresh': .1,
8 | 'llcrnrlon': 116, 'llcrnrlat': 36.6,
9 | 'urcrnrlon': 124, 'urcrnrlat': 40.2 }
10 | my_map = Basemap(**para)
11 | my_map.drawcoastlines(); my_map.drawmapboundary()
12 | ###############################################################################
13 | lon = 121.60001; lat = 38.91027
14 | x, y = my_map(lon, lat)
15 | my_map.plot(x, y, 'bo', markersize=12)
16 | plt.show()
17 | ###############################################################################
18 | my_map = Basemap(**para)
19 | my_map.drawcoastlines(); my_map.drawmapboundary()
20 | lons = [121.60001, 121.38617, 117.19723]
21 | lats = [38.91027, 37.53042, 39.12473]
22 | x, y = my_map(lons, lats)
23 | ###############################################################################
24 | my_map.plot(x, y, 'bo', markersize=10)
25 | plt.show()
26 | ###############################################################################
27 | my_map = Basemap(**para)
28 | my_map.drawcoastlines(); my_map.drawmapboundary()
29 | my_map.plot(x, y, marker=None,color='m')
30 | plt.show()
31 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec2_draw/test_3_text_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import matplotlib
5 | matplotlib.rcParams['font.family'] = 'sans-serif'
6 | matplotlib.rcParams['font.sans-serif'] = ['STKaiti']
7 | from mpl_toolkits.basemap import Basemap
8 | import matplotlib.pyplot as plt
9 | para = {'projection': 'merc', 'lat_0': 0, 'lon_0': 120,
10 | 'resolution': 'h', 'area_thresh': .1,
11 | 'llcrnrlon': 116, 'llcrnrlat': 36.6,
12 | 'urcrnrlon': 124, 'urcrnrlat': 40.2 }
13 | my_map = Basemap(**para)
14 | my_map.drawcoastlines(); my_map.drawmapboundary()
15 | ###############################################################################
16 | lon = 121.60001; lat = 38.91027
17 | x, y = my_map(lon, lat)
18 | plt.text(x, y, '大连',fontsize=12,fontweight='bold',
19 | ha='left',va='bottom',color='k')
20 | lon = 121.38617; lat = 37.53042
21 | x, y = my_map(lon, lat)
22 | plt.text(x, y, '烟台',fontsize=12,fontweight='bold',
23 | ha='left',va='center',color='k',
24 | bbox=dict(facecolor='b', alpha=0.2))
25 | plt.show()
26 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec2_draw/test_4_labelpoint_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import matplotlib
5 | matplotlib.rcParams['font.family'] = 'sans-serif'
6 | matplotlib.rcParams['font.sans-serif'] = ['STKaiti']
7 | from mpl_toolkits.basemap import Basemap
8 | import matplotlib.pyplot as plt
9 | para = {'projection': 'merc',
10 | 'lat_0': 0, 'lon_0': 120,
11 | 'resolution': 'h', 'area_thresh': .1,
12 | 'llcrnrlon': 116, 'llcrnrlat': 36.6,
13 | 'urcrnrlon': 124, 'urcrnrlat': 40.2 }
14 | my_map = Basemap(**para)
15 | my_map.drawcoastlines(); my_map.drawmapboundary()
16 | ###############################################################################
17 | lons = [121.60001, 121.38617, 117.19723]
18 | lats = [38.91027, 37.53042, 39.12473]
19 | x, y = my_map(lons, lats)
20 | my_map.plot(x, y, 'bo', markersize=10)
21 | ###############################################################################
22 | labels = ['大连', '烟台', '天津']
23 | for label, xpt, ypt in zip(labels, x, y):
24 | plt.text(xpt, ypt, label)
25 | plt.show()
26 | ###############################################################################
27 | my_map = Basemap(**para)
28 | my_map.drawcoastlines()
29 | my_map.drawmapboundary()
30 | x,y = my_map(lons, lats)
31 | my_map.plot(x, y, 'bo', markersize=10)
32 | for label, xpt, ypt in zip(labels, x, y):
33 | plt.text(xpt+10000, ypt+5000, label)
34 | plt.show()
35 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec3_with_gis_data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bukun/book_python_gis/cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e/part010/ch08_basemap/sec3_with_gis_data/__init__.py
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec3_with_gis_data/test_1_shapefile_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from mpl_toolkits.basemap import Basemap
5 | import matplotlib.pyplot as plt
6 | para = {'projection': 'tmerc', 'lat_0': 35, 'lon_0': -5,
7 | 'resolution': 'i', 'llcrnrlon': -30, 'llcrnrlat': 45,
8 | 'urcrnrlon': 20, 'urcrnrlat': 25 }
9 | mymap = Basemap(**para)
10 | ###############################################################################
11 | mymap.readshapefile('/gdata/GSHHS_h', 'comarques')
12 | plt.show()
13 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec3_with_gis_data/test_2_raster_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from mpl_toolkits.basemap import Basemap
5 | import matplotlib.pyplot as plt
6 | from osgeo import gdal
7 | from numpy import linspace
8 | from numpy import meshgrid
9 | para = {'projection': 'tmerc','lat_0': 0,'lon_0': 3,
10 | 'llcrnrlon': 1.819757266426611,
11 | 'llcrnrlat': 41.583851612359275,
12 | 'urcrnrlon': 1.841589961763497,
13 | 'urcrnrlat': 41.598674173123 }
14 | dem_tif = '/gdata/sample_files/dem.tiff'
15 | ###############################################################################
16 | p1 = plt.subplot(121)
17 | mymap = Basemap(**para)
18 | ds = gdal.Open(dem_tif)
19 | data = ds.ReadAsArray()
20 | x = linspace(0, mymap.urcrnrx, data.shape[1])
21 | y = linspace(0, mymap.urcrnry, data.shape[0])
22 | xx, yy = meshgrid(x, y)
23 | cs = mymap.contour(xx, yy, data, range(400, 1500, 100),
24 | cmap=plt.cm.cubehelix)
25 | ###############################################################################
26 | p2 = plt.subplot(122)
27 | mymap = Basemap(**para)
28 | ds = gdal.Open(dem_tif)
29 | data = ds.ReadAsArray()
30 | x = linspace(0, mymap.urcrnrx, data.shape[1])
31 | y = linspace(0, mymap.urcrnry, data.shape[0])
32 | xx, yy = meshgrid(x, y)
33 | cs = mymap.contour(xx, yy, data, range(400, 1500, 100),
34 | cmap=plt.cm.cubehelix)
35 | plt.clabel(cs, inline=True, fmt='%1.0f',
36 | fontsize=8, colors='k')
37 | plt.show()
38 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec4_example/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch08_basemap/sec4_example/test_1_data_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 |
--------------------------------------------------------------------------------
/part010/ch09_others/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec1_pyshp/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec1_pyshp/test_1_pyshp_intro_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | import shapefile
7 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec1_pyshp/test_4_pyshp_editing_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import shapefile
5 | e = shapefile.Editor(shapefile="xx_sf_point.shp")
6 | ###############################################################################
7 | e.point(0,0,10,2)
8 | e.record("Appended","Point")
9 | e.save('xx_sf_point')
10 | ###############################################################################
11 | e = shapefile.Editor(shapefile="xx_sf_line.shp")
12 | e.line(parts=[[[10,5],[15,5],[15,1],[13,3],[11,1]]])
13 | e.record('Appended','Line')
14 | e.save('xx_sf_line')
15 | ###############################################################################
16 | e = shapefile.Editor(shapefile="xx_sf_polygon.shp")
17 | e.poly(parts=[[[5.1,5],[9.9,5],[9.9,1],[7.5,3],[5.1,1]]])
18 | e.record("Appended","Polygon")
19 | e.save('xx_sf_polygon')
20 | ###############################################################################
21 | e = shapefile.Editor(shapefile="xx_sf_point.shp")
22 | e.delete(0)
23 | e.save('xx_sf_point')
24 | ###############################################################################
25 | e = shapefile.Editor(shapefile="xx_sf_polygon.shp")
26 | e.delete(-1)
27 | e.save('xx_sf_polygon')
28 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec2_geojson/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec2_geojson/fig_func.py:
--------------------------------------------------------------------------------
1 | import shapefile as shp
2 | import matplotlib
3 | matplotlib.use('Agg')
4 | import matplotlib.pyplot as plt
5 | from descartes import PolygonPatch
6 |
7 |
8 |
9 | import geojson
10 |
11 | uu = geojson.Polygon([
12 | [(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)],
13 | [(-5.21, 23.51), (15.21, -10.81), (-20.51, 1.51), (-5.21, 23.51)]
14 | ])
15 |
16 |
17 | point_instance = uu.__geo_interface__
18 |
19 | fig = plt.figure()
20 | ax = fig.gca()
21 | # for xx in range(polys.numRecords):
22 | # s = polys.shape(xx)
23 | # poly = s.__geo_interface__
24 | BLUE = '#6699cc'
25 |
26 | ax.add_patch(PolygonPatch(point_instance, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2))
27 | ax.axis('scaled')
28 |
29 | # plt.show()
30 |
31 | plt.savefig('uu.png')
32 | plt.clf()
--------------------------------------------------------------------------------
/part010/ch09_others/sec2_geojson/test_1_geojson_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec2_geojson/test_3_geojson_function_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import geojson
5 | my_point = geojson.Point((43.24, -1.532))
6 | my_point
7 | ###############################################################################
8 | dump = geojson.dumps(my_point, sort_keys=True)
9 | dump
10 | ###############################################################################
11 | geojson.loads(dump)
12 | ###############################################################################
13 | import geojson
14 | class MyPoint():
15 | def __init__(self, x, y):
16 | self.x = x
17 | self.y = y
18 | @property
19 | def __geo_interface__(self):
20 | return {'type': 'Point',
21 | 'coordinates': (self.x, self.y)}
22 |
23 | point_instance = MyPoint(52.235, -19.234)
24 | geojson.dumps(point_instance, sort_keys=True)
25 | ###############################################################################
26 | import geojson
27 | my_line = geojson.LineString([(-152.62, 51.21),
28 | (5.21, 10.69)])
29 | my_feature = geojson.Feature(geometry=my_line)
30 | list(geojson.utils.coords(my_feature))
31 | ###############################################################################
32 | import geojson
33 | new_point = geojson.utils.map_coords(lambda x: x/2,
34 | geojson.Point((-115.81, 37.24)))
35 | geojson.dumps(new_point, sort_keys=True)
36 | ###############################################################################
37 | import geojson
38 | geojson.utils.generate_random("LineString")
39 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec3_descartes/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec3_descartes/test_1_descartes_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | from matplotlib import pyplot as plt
6 | from shapely.geometry import LineString
7 | from descartes import PolygonPatch
8 | BLUE = '#6699cc'
9 | GRAY = '#999999'
10 | ###############################################################################
11 | def plot_line(ax, ob):
12 | x, y = ob.xy
13 | ax.plot(x, y, color=GRAY, linewidth=3,
14 | solid_capstyle='round', zorder=1)
15 | ###############################################################################
16 | def set_limits(ax, x0, xN, y0, yN):
17 | ax.set_xlim(x0, xN)
18 | ax.set_xticks(range(x0, xN+1))
19 | ax.set_ylim(y0, yN)
20 | ax.set_yticks(range(y0, yN+1))
21 | ax.set_aspect("equal")
22 | ###############################################################################
23 | line = LineString([(0, 0), (1, 1), (0, 2), (2, 2),
24 | (3, 1), (1, 0)])
25 | ###############################################################################
26 | fig = plt.figure(1, figsize=(10, 4), dpi=180)
27 | ax = fig.add_subplot(121)
28 | set_limits(ax, -1, 4, -1, 3)
29 | plot_line(ax, line)
30 | ###############################################################################
31 | dilated = line.buffer(0.5)
32 | patch1 = PolygonPatch(dilated, fc=GRAY, ec=GRAY,
33 | alpha=0.5, zorder=2)
34 | ax.add_patch(patch1)
35 | ###############################################################################
36 | ax = fig.add_subplot(122)
37 | patch2a = PolygonPatch(dilated, fc=GRAY, ec=GRAY,
38 | alpha=0.5, zorder=1)
39 | ax.add_patch(patch2a)
40 | set_limits(ax, -1, 4, -1, 3)
41 | ###############################################################################
42 | eroded = dilated.buffer(-0.3)
43 | polygon = eroded.__geo_interface__
44 | ###############################################################################
45 | patch2b = PolygonPatch(polygon, fc=BLUE, ec=BLUE,
46 | alpha=0.5, zorder=2)
47 | ax.add_patch(patch2b)
48 | plt.show()
49 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec3_descartes/test_2_example_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import shapefile as shp
5 | import matplotlib.pyplot as plt
6 | from descartes import PolygonPatch
7 | polys = shp.Reader('/gdata/GSHHS_c.shp')
8 | fig = plt.figure()
9 | ax = fig.gca()
10 | for xx in range(polys.numRecords):
11 | s = polys.shape(xx)
12 | poly = s.__geo_interface__
13 | BLUE = '#6699cc'
14 | ax.add_patch(PolygonPatch(poly, fc=BLUE, ec=BLUE,
15 | alpha=0.5, zorder=2))
16 | ax.axis('scaled')
17 | plt.show()
18 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec4_geopandas/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec4_geopandas/section_x_x.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | print('=' * 40)
3 | print(__file__)
4 | from helper.textool import get_tmp_file
5 |
6 | ################################################################################
7 |
8 | ################################################################################
9 |
10 | ################################################################################
11 |
12 | ################################################################################
13 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec4_geopandas/test_2_geopandas_frame_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | from matplotlib import pyplot as plt
5 | import geopandas as gpd
6 | world = gpd.read_file('/gdata/GSHHS_c.shp')
7 | world.head()
8 | ###############################################################################
9 | world.plot()
10 | plt.show()
11 | ###############################################################################
12 | world.geometry.name
13 | ###############################################################################
14 | world = world.rename(columns={'geometry': 'borders'}
15 | ).set_geometry('borders')
16 | world.geometry.name
17 | ###############################################################################
18 | world['centroid_column'] = world.centroid
19 | world = world.set_geometry('centroid_column')
20 | world.plot()
21 | plt.show()
22 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec4_geopandas/test_3_geopandas_map_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | import geopandas as gpd
5 | import matplotlib.pyplot as plt
6 | world = gpd.read_file('/gdata/GSHHS_c.shp')
7 | world['gdp_per_cap'] = world.area
8 | world.plot(column='gdp_per_cap')
9 | plt.show()
10 | ###############################################################################
11 | world.plot(column='gdp_per_cap', cmap='OrRd');
12 | plt.show()
13 | ###############################################################################
14 | world.plot(column='gdp_per_cap', cmap='OrRd',
15 | scheme='quantiles')
16 | plt.show()
17 | ###############################################################################
18 | cities = gpd.read_file(gpd.datasets.get_path(
19 | 'naturalearth_cities'))
20 | cities.plot(marker='*', color='green', markersize=5)
21 | ###############################################################################
22 | cities = cities.to_crs(world.crs)
23 | ###############################################################################
24 | base = world.plot(color='white')
25 | cities.plot(ax=base, marker='o',color='red',markersize=5)
26 | plt.show()
27 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec4_geopandas/test_6_proj_x_x.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | ###############################################################################
4 | ###############################################################################
5 | ###############################################################################
6 | ###############################################################################
7 | ###############################################################################
8 | import geopandas as gpd
9 | import matplotlib.pyplot as plt
10 | world = gpd.read_file('/gdata/GSHHS_c.shp')
11 | world.crs
12 | ###############################################################################
13 | world.crs = {'init': 'epsg:3857'}
14 | world.crs
15 | ###############################################################################
16 | world.crs = {'init': 'epsg:4326'}
17 | ###############################################################################
18 | world1 = world.to_crs({'init': 'epsg:3395'})
19 | ###############################################################################
20 | world = world.to_crs(epsg=3395)
21 | world.plot()
22 | plt.show()
23 |
--------------------------------------------------------------------------------
/part010/ch09_others/sec5_folium/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/part010/ch99_append/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
--------------------------------------------------------------------------------
/part010/ch99_append/sec010_the_book/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
--------------------------------------------------------------------------------
/part010/figs/test_shapely_buffer.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from matplotlib import pyplot
4 | from shapely.geometry import LineString
5 | from descartes import PolygonPatch
6 |
7 | from helper.textool import get_tmp_file
8 |
9 |
10 | BLUE = '#6699cc'
11 | GRAY = '#999999'
12 |
13 | def plot_line(ax, ob):
14 | x, y = ob.xy
15 | ax.plot(x, y, color=GRAY, linewidth=3, solid_capstyle='round', zorder=1)
16 |
17 | line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
18 |
19 | fig = pyplot.figure(1, figsize=(10, 4), dpi=180)
20 |
21 | # 1
22 | ax = fig.add_subplot(121)
23 |
24 | plot_line(ax, line)
25 |
26 | dilated = line.buffer(0.5)
27 | patch1 = PolygonPatch(dilated, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
28 | ax.add_patch(patch1)
29 |
30 | #2
31 | ax = fig.add_subplot(122)
32 |
33 | patch2a = PolygonPatch(dilated, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1)
34 | ax.add_patch(patch2a)
35 |
36 | eroded = dilated.buffer(-0.3)
37 |
38 | # GeoJSON-like data works as well
39 |
40 | polygon = eroded.__geo_interface__
41 | # >>> geo['type']
42 | # 'Polygon'
43 | # >>> geo['coordinates'][0][:2]
44 | # ((0.50502525316941682, 0.78786796564403572), (0.5247963548222736, 0.8096820147509064))
45 | patch2b = PolygonPatch(polygon, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
46 | ax.add_patch(patch2b)
47 |
48 | # pyplot.savefig('figs/xx_shapely_buffer.png')
49 |
50 | pyplot.savefig(get_tmp_file(__file__, '1'), bbox_inches='tight')
51 | pyplot.savefig(get_tmp_file(__file__, '1', file_ext='pdf'), bbox_inches='tight')
52 | pyplot.clf()
--------------------------------------------------------------------------------
/run_foo.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | python3 extract_py_from_latex.py
3 | # nosetests3 --exe -v -d -s part010/ch07_mapnik/
4 | #nosetests3 -v -d -s --exe part010/ch09_others/sec5_folium/
5 | #cp -r folium_*.html /opt/tmp/
6 |
7 |
8 | # nosetests3 -v -d -s --exe part010/ch05_shapely/sec4_spatial_analysis
9 | # nosetests3 -v -d -s --exe part010/ch08_basemap
10 |
11 | nosetests3 -v -d -s --exe part010/ch08_basemap/sec4_example/
12 |
--------------------------------------------------------------------------------
/run_test.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 |
4 |
5 | # ogr2ogr -f SQLite -dsco SPATIALITE=YES spalite.db /gdata/stats_county.shp -nlt polygon
6 |
7 |
8 | # ogr2ogr -f 'SQLite' -lco SRID=4326 -nlt POINT -append spalite.db /gdata/prov_capital.shp
9 |
10 |
11 | python3 extract_py_from_latex.py
12 | rm -f spalite.db
13 |
14 | nosetests3 -v -d -s --exe part010/ch01_introduction
15 | nosetests3 -v -d -s --exe part010/ch02_gdal
16 | nosetests3 -v -d -s --exe part010/ch03_ogr
17 | nosetests3 -v -d -s --exe part010/ch04_proj
18 | nosetests3 -v -d -s --exe part010/ch05_shapely
19 |
20 | ogr2ogr -f SQLite -dsco SPATIALITE=YES spalite.db /gdata/county_popu.shp -nlt polygon
21 | ogr2ogr -f 'SQLite' -lco SRID=4326 -nlt LINESTRING -append spalite.db /gdata/hyd2_4l.shp
22 | nosetests3 -v -d -s --exe part010/ch06_spatialite
23 |
24 | nosetests3 -v -d -s --exe part010/ch07_mapnik
25 | nosetests3 -v -d -s --exe part010/ch08_basemap
26 | nosetests3 -v -d -s --exe part010/ch09_others
27 | nosetests3 -v -d -s --exe part010/ch99_append
28 |
29 |
--------------------------------------------------------------------------------
/run_ts.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | python3 extract_py_from_latex.py
4 |
5 | rm -f spalite.db
6 | ogr2ogr -f SQLite -dsco SPATIALITE=YES spalite.db /gdata/county_popu.shp -nlt polygon
7 | ogr2ogr -f 'SQLite' -lco SRID=4326 -nlt LINESTRING -append spalite.db /gdata/hyd2_4l.shp
8 |
9 | nosetests3 -v -d -s --exe ./part010/ch06_spatialite/sec4_access_sqlite_via_python/
10 |
11 |
12 |
13 | nosetests3 -v -d -s --exe ./part010/ch06_spatialite/
14 |
15 |
16 |
--------------------------------------------------------------------------------