{ "cells": [ { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import folium\n", "import geopandas as gpd\n", "from branca.colormap import *\n", "import json\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "#005a32\n" ] }, { "data": { "text/html": [ "03" ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "colormap = linear.YlGn.scale(\n", " 0,\n", " 3)\n", "\n", "print(colormap(5.0))\n", "colormap\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class Map in module folium.folium:\n", "\n", "class Map(folium.map.LegacyMap)\n", " | Create a Map with Folium and Leaflet.js\n", " | \n", " | Generate a base map of given width and height with either default\n", " | tilesets or a custom tileset URL. The following tilesets are built-in\n", " | to Folium. Pass any of the following to the \"tiles\" keyword:\n", " | \n", " | - \"OpenStreetMap\"\n", " | - \"Mapbox Bright\" (Limited levels of zoom for free tiles)\n", " | - \"Mapbox Control Room\" (Limited levels of zoom for free tiles)\n", " | - \"Stamen\" (Terrain, Toner, and Watercolor)\n", " | - \"Cloudmade\" (Must pass API key)\n", " | - \"Mapbox\" (Must pass API key)\n", " | - \"CartoDB\" (positron and dark_matter)\n", " | \n", " | You can pass a custom tileset to Folium by passing a Leaflet-style\n", " | URL to the tiles parameter:\n", " | http://{s}.yourtiles.com/{z}/{x}/{y}.png\n", " | \n", " | Parameters\n", " | ----------\n", " | location: tuple or list, default None\n", " | Latitude and Longitude of Map (Northing, Easting).\n", " | width: pixel int or percentage string (default: '100%')\n", " | Width of the map.\n", " | height: pixel int or percentage string (default: '100%')\n", " | Height of the map.\n", " | tiles: str, default 'OpenStreetMap'\n", " | Map tileset to use. Can choose from a list of built-in tiles,\n", " | pass a custom URL or pass `None` to create a map without tiles.\n", " | API_key: str, default None\n", " | API key for Cloudmade or Mapbox tiles.\n", " | max_zoom: int, default 18\n", " | Maximum zoom depth for the map.\n", " | zoom_start: int, default 10\n", " | Initial zoom level for the map.\n", " | attr: string, default None\n", " | Map tile attribution; only required if passing custom tile URL.\n", " | detect_retina: bool, default False\n", " | If true and user is on a retina display, it will request four\n", " | tiles of half the specified size and a bigger zoom level in place\n", " | of one to utilize the high resolution.\n", " | crs : str, default 'EPSG3857'\n", " | Defines coordinate reference systems for projecting geographical points\n", " | into pixel (screen) coordinates and back.\n", " | You can use Leaflet's values :\n", " | * EPSG3857 : The most common CRS for online maps, used by almost all\n", " | free and commercial tile providers. Uses Spherical Mercator projection.\n", " | Set in by default in Map's crs option.\n", " | * EPSG4326 : A common CRS among GIS enthusiasts.\n", " | Uses simple Equirectangular projection.\n", " | * EPSG3395 : Rarely used by some commercial tile providers.\n", " | Uses Elliptical Mercator projection.\n", " | * Simple : A simple CRS that maps longitude and latitude into\n", " | x and y directly. May be used for maps of flat surfaces\n", " | (e.g. game maps). Note that the y axis should still be inverted\n", " | (going from bottom to top).\n", " | control_scale : bool, default False\n", " | Whether to add a control scale on the map.\n", " | prefer_canvas : bool, default False\n", " | Forces Leaflet to use the Canvas back-end (if available) for\n", " | vector layers instead of SVG. This can increase performance\n", " | considerably in some cases (e.g. many thousands of circle\n", " | markers on the map).\n", " | no_touch : bool, default False\n", " | Forces Leaflet to not use touch events even if it detects them.\n", " | disable_3d : bool, default False\n", " | Forces Leaflet to not use hardware-accelerated CSS 3D\n", " | transforms for positioning (which may cause glitches in some\n", " | rare environments) even if they're supported.\n", " | \n", " | Returns\n", " | -------\n", " | Folium LegacyMap Object\n", " | \n", " | Examples\n", " | --------\n", " | >>> map = folium.LegacyMap(location=[45.523, -122.675],\n", " | ... width=750, height=500)\n", " | >>> map = folium.LegacyMap(location=[45.523, -122.675],\n", " | tiles='Mapbox Control Room')\n", " | >>> map = folium.LegacyMap(location=(45.523, -122.675), max_zoom=20,\n", " | tiles='Cloudmade', API_key='YourKey')\n", " | >>> map = folium.LegacyMap(location=[45.523, -122.675], zoom_start=2,\n", " | tiles=('http://{s}.tiles.mapbox.com/v3/'\n", " | 'mapbox.control-room/{z}/{x}/{y}.png'),\n", " | attr='Mapbox attribution')\n", " | \n", " | Method resolution order:\n", " | Map\n", " | folium.map.LegacyMap\n", " | branca.element.MacroElement\n", " | branca.element.Element\n", " | __builtin__.object\n", " | \n", " | Methods defined here:\n", " | \n", " | choropleth(self, geo_path=None, geo_str=None, data_out='data.json', data=None, columns=None, key_on=None, threshold_scale=None, fill_color='blue', fill_opacity=0.6, line_color='black', line_weight=1, line_opacity=1, legend_name='', topojson=None, reset=False, smooth_factor=None, highlight=None)\n", " | Apply a GeoJSON overlay to the map.\n", " | \n", " | Plot a GeoJSON overlay on the base map. There is no requirement\n", " | to bind data (passing just a GeoJSON plots a single-color overlay),\n", " | but there is a data binding option to map your columnar data to\n", " | different feature objects with a color scale.\n", " | \n", " | If data is passed as a Pandas DataFrame, the \"columns\" and \"key-on\"\n", " | keywords must be included, the first to indicate which DataFrame\n", " | columns to use, the second to indicate the layer in the GeoJSON\n", " | on which to key the data. The 'columns' keyword does not need to be\n", " | passed for a Pandas series.\n", " | \n", " | Colors are generated from color brewer (http://colorbrewer2.org/)\n", " | sequential palettes on a D3 threshold scale. The scale defaults to the\n", " | following quantiles: [0, 0.5, 0.75, 0.85, 0.9]. A custom scale can be\n", " | passed to `threshold_scale` of length <=6, in order to match the\n", " | color brewer range.\n", " | \n", " | TopoJSONs can be passed as \"geo_path\", but the \"topojson\" keyword must\n", " | also be passed with the reference to the topojson objects to convert.\n", " | See the topojson.feature method in the TopoJSON API reference:\n", " | https://github.com/mbostock/topojson/wiki/API-Reference\n", " | \n", " | \n", " | Parameters\n", " | ----------\n", " | geo_path: string, default None\n", " | URL or File path to your GeoJSON data\n", " | geo_str: string, default None\n", " | String of GeoJSON, alternative to geo_path\n", " | data_out: string, default 'data.json'\n", " | Path to write Pandas DataFrame/Series to JSON if binding data\n", " | data: Pandas DataFrame or Series, default None\n", " | Data to bind to the GeoJSON.\n", " | columns: dict or tuple, default None\n", " | If the data is a Pandas DataFrame, the columns of data to be bound.\n", " | Must pass column 1 as the key, and column 2 the values.\n", " | key_on: string, default None\n", " | Variable in the GeoJSON file to bind the data to. Must always\n", " | start with 'feature' and be in JavaScript objection notation.\n", " | Ex: 'feature.id' or 'feature.properties.statename'.\n", " | threshold_scale: list, default None\n", " | Data range for D3 threshold scale. Defaults to the following range\n", " | of quantiles: [0, 0.5, 0.75, 0.85, 0.9], rounded to the nearest\n", " | order-of-magnitude integer. Ex: 270 rounds to 200, 5600 to 6000.\n", " | fill_color: string, default 'blue'\n", " | Area fill color. Can pass a hex code, color name, or if you are\n", " | binding data, one of the following color brewer palettes:\n", " | 'BuGn', 'BuPu', 'GnBu', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'RdPu',\n", " | 'YlGn', 'YlGnBu', 'YlOrBr', and 'YlOrRd'.\n", " | fill_opacity: float, default 0.6\n", " | Area fill opacity, range 0-1.\n", " | line_color: string, default 'black'\n", " | GeoJSON geopath line color.\n", " | line_weight: int, default 1\n", " | GeoJSON geopath line weight.\n", " | line_opacity: float, default 1\n", " | GeoJSON geopath line opacity, range 0-1.\n", " | legend_name: string, default empty string\n", " | Title for data legend.\n", " | topojson: string, default None\n", " | If using a TopoJSON, passing \"objects.yourfeature\" to the topojson\n", " | keyword argument will enable conversion to GeoJSON.\n", " | reset: boolean, default False\n", " | Remove all current geoJSON layers, start with new layer\n", " | smooth_factor: float, default None\n", " | How much to simplify the polyline on each zoom level. More means\n", " | better performance and smoother look, and less means more accurate\n", " | representation. Leaflet defaults to 1.0.\n", " | highlight: boolean, default False\n", " | Enable highlight functionality when hovering over a GeoJSON area.\n", " | \n", " | Returns\n", " | -------\n", " | GeoJSON data layer in obj.template_vars\n", " | \n", " | Examples\n", " | --------\n", " | >>> m.choropleth(geo_path='us-states.json', line_color='blue',\n", " | ... line_weight=3)\n", " | >>> m.choropleth(geo_path='geo.json', data=df,\n", " | ... columns=['Data 1', 'Data 2'],\n", " | ... key_on='feature.properties.myvalue',\n", " | ... fill_color='PuBu',\n", " | ... threshold_scale=[0, 20, 30, 40, 50, 60])\n", " | >>> m.choropleth(geo_path='countries.json',\n", " | ... topojson='objects.countries')\n", " | >>> m.choropleth(geo_path='geo.json', data=df,\n", " | ... columns=['Data 1', 'Data 2'],\n", " | ... key_on='feature.properties.myvalue',\n", " | ... fill_color='PuBu',\n", " | ... threshold_scale=[0, 20, 30, 40, 50, 60],\n", " | ... highlight=True)\n", " | \n", " | fit_bounds(self, bounds, padding_top_left=None, padding_bottom_right=None, padding=None, max_zoom=None)\n", " | Fit the map to contain a bounding box with the\n", " | maximum zoom level possible.\n", " | \n", " | Parameters\n", " | ----------\n", " | bounds: list of (latitude, longitude) points\n", " | Bounding box specified as two points [southwest, northeast]\n", " | padding_top_left: (x, y) point, default None\n", " | Padding in the top left corner. Useful if some elements in\n", " | the corner, such as controls, might obscure objects you're zooming\n", " | to.\n", " | padding_bottom_right: (x, y) point, default None\n", " | Padding in the bottom right corner.\n", " | padding: (x, y) point, default None\n", " | Equivalent to setting both top left and bottom right padding to\n", " | the same value.\n", " | max_zoom: int, default None\n", " | Maximum zoom to be used.\n", " | \n", " | Examples\n", " | --------\n", " | >>> map.fit_bounds([[52.193636, -2.221575], [52.636878, -1.139759]])\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from folium.map.LegacyMap:\n", " | \n", " | __init__(self, location=None, width=u'100%', height=u'100%', left=u'0%', top=u'0%', position=u'relative', tiles=u'OpenStreetMap', API_key=None, max_zoom=18, min_zoom=1, zoom_start=10, continuous_world=False, world_copy_jump=False, no_wrap=False, attr=None, min_lat=-90, max_lat=90, min_lon=-180, max_lon=180, max_bounds=True, detect_retina=False, crs=u'EPSG3857', control_scale=False, prefer_canvas=False, no_touch=False, disable_3d=False)\n", " | \n", " | add_tile_layer(self, tiles=u'OpenStreetMap', name=None, API_key=None, max_zoom=18, min_zoom=1, continuous_world=False, attr=None, active=False, detect_retina=False, no_wrap=False, **kwargs)\n", " | Add a tile layer to the map. See TileLayer for options.\n", " | \n", " | render(self, **kwargs)\n", " | Renders the HTML representation of the element.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from branca.element.Element:\n", " | \n", " | add_child(self, child, name=None, index=None)\n", " | Add a child.\n", " | \n", " | add_children(self, child, name=None, index=None)\n", " | Add a child.\n", " | \n", " | add_to(self, parent, name=None, index=None)\n", " | Add element to a parent.\n", " | \n", " | get_bounds(self)\n", " | Computes the bounds of the object and all it's children\n", " | in the form [[lat_min, lon_min], [lat_max, lon_max]].\n", " | \n", " | get_name(self)\n", " | Returns a string representation of the object.\n", " | This string has to be unique and to be a python and\n", " | javascript-compatible\n", " | variable name.\n", " | \n", " | get_root(self)\n", " | Returns the root of the elements tree.\n", " | \n", " | save(self, outfile, close_file=True, **kwargs)\n", " | Saves an Element into a file.\n", " | \n", " | Parameters\n", " | ----------\n", " | outfile : str or file object\n", " | The file (or filename) where you want to output the html.\n", " | close_file : bool, default True\n", " | Whether the file has to be closed after write.\n", " | \n", " | to_dict(self, depth=-1, ordered=True, **kwargs)\n", " | Returns a dict representation of the object.\n", " | \n", " | to_json(self, depth=-1, **kwargs)\n", " | Returns a JSON representation of the object.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from branca.element.Element:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", "\n" ] } ], "source": [ "help(folium.Map)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "json_fn = r'd:\\test\\manzese_valid\\gis_files\\manzese_culverts_geo.json'\n", "key = 'width_flag'\n", "# geo_json_data = json.load(open(json_fn))\n", "gpd_obj = gpd.read_file(json_fn)\n", "# make a style column\n", "# geoms = gpd_obj.buffer(0.0001)\n", "\n", "# gpd_obj['geometry'] = geoms\n", "gpd_obj['style'] = [\n", " {'color': 'black', 'weight': 8} for value in gpd_obj[key]\n", " ]\n", "\n", "step = StepColormap(['green', 'yellow', 'orange', 'red'],\n", " vmin=-0.5, vmax=3.5, index=[-0.5, 0.5, 1.5, 2.5, 3.5],\n", " caption='step')\n", "\n", "m = folium.Map()\n", "# m = folium.Map(min_lat=min_lat, min_lon=min_lon, max_lat=max_lat, max_lon=max_lon)\n", "m.fit_bounds([[-6.807052, 39.2226719], [-6.7851343, 39.2397977]])\n", "# folium.TileLayer('Mapbox Bright').add_to(m)\n", "# color_dict = {value: colormap(value) for value in gpd_obj[key]}\n", "# values = gpd_obj[key]\n", "# folium.GeoJson(geo_json_data).add_to(m)\n", "feature_group = folium.FeatureGroup(name='Channels', overlay=False)\n", "\n", "folium.GeoJson(\n", " gpd_obj,\n", " name='channels1'\n", " ).add_to(feature_group)\n", "\n", "gpd_obj['style'] = [\n", " {'color': step(value), 'weight': 6} for value in gpd_obj[key]\n", " ]\n", "folium.GeoJson(\n", " gpd_obj,\n", " name='channels2',\n", " ).add_to(feature_group)\n", "feature_group2 = folium.FeatureGroup(name='Channels2', overlay=False)\n", "\n", "m.add_child(feature_group)\n", "# feature_group.add_to(m)\n", "feature_group2 = folium.FeatureGroup(name='Channels2')\n", "step.caption = 'Quality 0: Correct 1: Value outside range 2: Incorrect data type 3: no value'\n", "m.add_child(step)\n", "folium.LayerControl().add_to(m) #Add layer control to toggle on/off\n", "# step.tick_labels(['a', 'b', 'c', 'd', ''])\n", "m" ] }, { "cell_type": "code", "execution_count": 168, "metadata": { "collapsed": false }, "outputs": [], "source": [ "json_fn = r'd:\\test\\manzese_valid\\gis_files\\manzese_buildings_geo.json'\n", "key = 'amenity_flag'\n", "# geo_json_data = json.load(open(json_fn))\n", "gpd_obj = gpd.read_file(json_fn)\n", "# make a style column\n", "# geoms = gpd_obj.buffer(0.0001)\n", "# colormap = cm.StepColormap(['green', 'yellow', 'orange', 'red'],\n", "# vmin=-0.5, vmax=3.5, index=[-0.5, 0.5, 1.5, 2.5, 3.5],\n", "# caption='step')\n", "\n", "# # gpd_obj['geometry'] = geoms\n", "# gpd_obj['style'] = [\n", "# {'color': 'black', 'weight': 1} for value in gpd_obj[key]\n", "# ]\n", "# min_lat = -6.807052\n", "# max_lat = -6.7851343\n", "# min_lon = 39.2226719\n", "# max_lon = 39.2397977\n", "# # m = folium.Map([-6.792, 39.23], zoom_start=15)\n", "# m = folium.Map()\n", "# m.fit_bounds([[-6.807052, 39.2226719], [-6.7851343, 39.2397977]])\n", "# # color_dict = {value: colormap(value) for value in gpd_obj[key]}\n", "# # values = gpd_obj[key]\n", "# # folium.GeoJson(geo_json_data).add_to(m)\n", "# # folium.GeoJson(\n", "# # gpd_obj,\n", "# # name='buildings'\n", "# # ).add_to(m)\n", "\n", "# gpd_obj['style'] = [\n", "# {'fillColor': 'black', 'color': colormap(value), 'weight': 2} for value in gpd_obj[key]\n", "# ]\n", "# folium.GeoJson(\n", "# gpd_obj[0:100],\n", "# name='buildings',\n", "# ).add_to(m)\n", "# folium.LayerControl().add_to(m) #Add layer control to toggle on/off\n", "# m\n", "# # m.save('buildings.html')" ] }, { "cell_type": "code", "execution_count": 169, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "Index([ u'addr:housenumber', u'addr:housenumber_flag',\n", " u'addr:street', u'addr:street_flag',\n", " u'amenity', u'amenity_flag',\n", " u'bed_count', u'bed_count_flag',\n", " u'building:levels', u'building:levels_flag',\n", " u'building:material', u'building:material_flag',\n", " u'geometry', u'name',\n", " u'name_flag', u'office',\n", " u'office_flag', u'osm_id',\n", " u'osm_id_flag', u'osm_way_id',\n", " u'osm_way_id_flag', u'religion',\n", " u'religion_flag', u'shop',\n", " u'shop_flag', u'tourism',\n", " u'tourism_flag'],\n", " dtype='object')" ] }, "execution_count": 169, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gpd_obj.keys()" ] }, { "cell_type": "code", "execution_count": 178, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "161905\n" ] } ], "source": [ "print len(gpd_obj['geometry'])\n", "test = gpd_obj.geometry[0:10000]\n", "centr = test.centroid" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 72, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m = folium.Map()\n", "json_fn = r'd:\\test\\manzese_valid\\gis_files\\manzese_buildings_geo.json'\n", "key = 'amenity_flag'\n", "# geo_json_data = json.load(open(json_fn))\n", "gpd_obj = gpd.read_file(json_fn)\n", "m.fit_bounds([[-6.807052, 39.2226719], [-6.7851343, 39.2397977]])\n", "\n", "m.choropleth(geo_str=gpd_obj.geometry.to_json(), data=gpd_obj[key],\n", "columns=[key, key],\n", "key_on='feature.id',\n", "fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2,\n", "legend_name=key)\n", "m" ] }, { "cell_type": "code", "execution_count": 135, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# m = folium.Map(tiles=\"Mapbox\",\n", "# API_key=\"sk.eyJ1IjoiaGN3aW5zZW1pdXMiLCJhIjoiY2oycWowYjNmMDA1MjJ3bzd1c2x4NGNveiJ9.L6cHN3TbVFmS05aIJ_dqGA\")\n", "# m = folium.Map(location=[45.372, -121.6972],\n", "# zoom_start=12,\n", "# tiles='\"http://{s}.tiles.mapbox.com/v4/wtgeographer.2fb7fc73/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiaGN3aW5zZW1pdXMiLCJhIjoiY2l2MHd3aDN4MDA0OTJ6dDU2Y2F6MWk0dCJ9.mLH0b46r4cHNdb1w9-dLcQ',\n", "# attr='XXX Mapbox Attribution')\n", "m = folium.Map(location=[45.5236, -122.6750],\n", "# API_key='pk.eyJ1IjoiaGN3aW5zZW1pdXMiLCJhIjoiY2l2MHd3aDN4MDA0OTJ6dDU2Y2F6MWk0dCJ9.mLH0b46r4cHNdb1w9-dLcQ'\n", " )\n", "folium.TileLayer('Mapbox',\n", " API_key='pk.eyJ1IjoiaGN3aW5zZW1pdXMiLCJhIjoiY2l2MHd3aDN4MDA0OTJ6dDU2Y2F6MWk0dCJ9.mLH0b46r4cHNdb1w9-dLcQ',\n", " attr='Some attribution').add_to(m)\n", "folium.LayerControl().add_to(m) #Add layer control to toggle on/off\n", "\n", "m.save('test.html')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [conda root]", "language": "python", "name": "conda-root-py" } }, "nbformat": 4, "nbformat_minor": 1 }