def test_generate_thumbnail_name_map(self, uuid_mock, layers_mock): layers_mock.return_value = [MapLayer()] uuid_mock.return_value = str(uuid.uuid4()) map_name = thumbnails._generate_thumbnail_name(Map.objects.first()) self.assertIsNotNone( re.match(f"map-{self.re_uuid}-thumb.png", map_name, re.I), "Map name should meet a provided pattern" )
def add_layer_to_mapstory(self, mapstory, layer, stack_order, style): map = mapstory.chapters[0] maplayer = MapLayer() maplayer.map = map maplayer.name = layer.name maplayer.stack_order = stack_order maplayer.opacity = 1.0 maplayer.fixed = False maplayer.visibility = True maplayer.source_params = u'{"lazy": true, "name": "local geoserver", "title": "Local Geoserver", "ptype": "gxp_wmscsource", "restUrl": "/gs/rest", "isVirtualService": false, "mapLayerRequiresServer": true}' maplayer.layer_config = "" maplayer.styles = style maplayer.save()
def test_datasets_locations_simple_map(self): dataset = Dataset.objects.get(title_en="theaters_nyc") map = Map.objects.get(title_en="theaters_nyc_map") MapLayer( map=map, name="Meteorite_Landings_from_NASA_Open_Data_Portal1", current_style="test_style", ows_url="https://maps.geo-solutions.it/geoserver/wms", ).save() locations, bbox = thumbnails._datasets_locations(map) self.assertFalse(bbox, "Expected BBOX not to be calculated") self.assertEqual(locations, [[settings.OGC_SERVER["default"]["LOCATION"], ["geonode:Meteorite_Landings_from_NASA_Open_Data_Portal1", dataset.alternate], ["test_style", "theaters_nyc"]]])
def test_datasets_locations_simple_map(self): dataset = Dataset.objects.get(title_en="theaters_nyc") map = Map.objects.get(title_en="theaters_nyc_map") MapLayer( map=map, name="Meteorite_Landings_from_NASA_Open_Data_Portal1", stack_order=1, visibility=True, ows_url="https://maps.geo-solutions.it/geoserver/wms", dataset_params="""{\"id\": 1, \"title\": \"Open Street Map\", \"style\": \"test_style\", \"type\": \"osm\", \"singleTile\": false, \"dimensions\": [], \"hideLoading\": false, \"handleClickOnLayer\": false, \"useForElevation\": false, \"hidden\": false, \"extraParams\": {\"msId\": \"mapnik__0\"}, \"wrapDateLine\": true, \"displayOutsideMaxExtent\": true}""" ).save() locations, bbox = thumbnails._datasets_locations(map) self.assertFalse(bbox, "Expected BBOX not to be calculated") self.assertEqual(locations, [[settings.OGC_SERVER["default"]["LOCATION"], ["geonode:Meteorite_Landings_from_NASA_Open_Data_Portal1", dataset.alternate], ["test_style", "theaters_nyc"]]])
def add_to_map(req, id, typename): if req.method != 'POST': return HttpResponse('POST required', status=400) mapobj = get_object_or_404(Map, id=id) if mapobj.owner != req.user and not req.user.has_perm( 'maps.change_map', mapobj): return HttpResponse('Not sufficient permissions', status=401) layer = get_object_or_404(Layer, typename=typename) existing = MapLayer.objects.filter(map=mapobj) vs_url = settings.GEOSERVER_BASE_URL + '%s/%s/wms' % tuple( layer.typename.split(':')) stack_order = max([l.stack_order for l in existing]) + 1 # have to use local name, not full typename when using ows_url maplayer = MapLayer(name=layer.name, ows_url=vs_url, map=mapobj, stack_order=stack_order) maplayer.save() # if bounding box is equivalent to default, compute and save ints = lambda t: map(int, t) if ints(mapobj.center) == ints( forward_mercator(settings.DEFAULT_MAP_CENTER)): bbox = layer.resource.latlon_bbox[0:4] # @todo copy-paste from geonode.maps.views - extract this for reuse minx, maxx, miny, maxy = [float(c) for c in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 center = forward_mercator((x, y)) if center[1] == float('-inf'): center = (center[0], 0) if maxx == minx: width_zoom = 15 else: width_zoom = math.log(360 / (maxx - minx), 2) if maxy == miny: height_zoom = 15 else: height_zoom = math.log(360 / (maxy - miny), 2) mapobj.center_x = center[0] mapobj.center_y = center[1] mapobj.zoom = math.ceil(min(width_zoom, height_zoom)) mapobj.save() return HttpResponse('OK', status=200)
def add_mapstory(self): mapstory = MapStory() mapstory.name = "test_case1" mapstory.owner = self.admin_user mapstory.uuid = str(uuid.uuid1()) mapstory.save() map = Map() map.story = mapstory map.chapter_index = 0 map.title = "test_case" map.projection = 'EPSG:4326' map.owner = mapstory.owner map.uuid = str(uuid.uuid1()) map.zoom = 4 map.center_x = 0 map.center_y = 0 map.set_bounds_from_center_and_zoom(map.center_x, map.center_y, map.zoom) map.save() mapstory.chapter_list.add(map) mapstory.save() # background maplayer_background = MapLayer() maplayer_background.map = map maplayer_background.name = "control-room" maplayer_background.stack_order = 4 maplayer_background.opacity = 1.0 maplayer_background.fixed = False maplayer_background.visibility = True maplayer_background.source_params = u'{"hidden": true, "ptype": "gxp_mapboxsource"}' maplayer_background.layer_config = "" maplayer_background.group = "background" maplayer_background.save() # map.layers.add(maplayer) map.save() return mapstory
def add_layers_to_map_config(request, map_obj, layer_names, add_base_layers=True): DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request) bbox = None layers = [] for layer_name in layer_names: try: layer = _resolve_layer(request, layer_name) except ObjectDoesNotExist: # bad layer, skip continue if not layer.is_published: # invisible layer, skip inclusion continue if not request.user.has_perm('view_resourcebase', obj=layer.get_self_resource()): # invisible layer, skip inclusion continue layer_bbox = layer.bbox # assert False, str(layer_bbox) if bbox is None: bbox = list(layer_bbox[0:4]) else: bbox[0] = min(bbox[0], layer_bbox[0]) bbox[1] = max(bbox[1], layer_bbox[1]) bbox[2] = min(bbox[2], layer_bbox[2]) bbox[3] = max(bbox[3], layer_bbox[3]) config = layer.attribute_config() # Add required parameters for a WM layer title = 'No title' if layer.title: title = layer.title config["title"] = title config["queryable"] = True config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \ else llbbox_to_mercator([float(coord) for coord in bbox]) if layer.storeType == "remoteStore": service = layer.service # Probably not a good idea to send the access token to every remote service. # This should never match, so no access token should be # sent to remote services. ogc_server_url = urlparse.urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc service_url = urlparse.urlsplit(service.base_url).netloc access_token = request.session[ 'access_token'] if request and 'access_token' in request.session else None if access_token and ogc_server_url == service_url and 'access_token' not in service.base_url: url = service.base_url + '?access_token=' + access_token else: url = service.base_url maplayer = MapLayer(map=map_obj, name=layer.alternate, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True, source_params=json.dumps({ "ptype": service.ptype, "remote": True, "url": url, "name": service.name })) else: ogc_server_url = urlparse.urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc layer_url = urlparse.urlsplit(layer.ows_url).netloc if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url: url = layer.ows_url + '?access_token=' + access_token else: url = layer.ows_url maplayer = MapLayer( map=map_obj, name=layer.alternate, ows_url=url, # use DjangoJSONEncoder to handle Decimal values layer_params=json.dumps(config, cls=DjangoJSONEncoder), visibility=True) layers.append(maplayer) if bbox is not None: minx, maxx, miny, maxy = [float(coord) for coord in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') == "EPSG:4326": center = list((x, y)) else: center = list(forward_mercator((x, y))) if center[1] == float('-inf'): center[1] = 0 BBOX_DIFFERENCE_THRESHOLD = 1e-5 # Check if the bbox is invalid valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD if valid_x: width_zoom = math.log(360 / abs(maxx - minx), 2) else: width_zoom = 15 if valid_y: height_zoom = math.log(360 / abs(maxy - miny), 2) else: height_zoom = 15 map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) map_obj.handle_moderated_uploads() if add_base_layers: layers_to_add = DEFAULT_BASE_LAYERS + layers else: layers_to_add = layers config = map_obj.viewer_json(request, *layers_to_add) config['fromLayer'] = True return config
def get_context_data(self, **kwargs): request = self.request if request and 'access_token' in request.session: access_token = request.session['access_token'] else: access_token = None DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request) layers = Layer.objects.all() if request.method == 'GET' and 'copy' in request.GET: """Prepare context data.""" request = self.request mapid = self.request.GET['copy'] map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) config = map_obj.viewer_json(request) # list all required layers map_layers = MapLayer.objects.filter( map_id=mapid).order_by('stack_order') context = { 'config': json.dumps(config), 'create': False, 'layers': layers, 'map': map_obj, 'map_layers': map_layers, 'preview': getattr(settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'leaflet') } return context else: if request.method == 'GET': params = request.GET elif request.method == 'POST': params = request.POST else: return self.render_to_response(status=405) if 'layer' in params: bbox = None map_obj = Map(projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857')) for layer_name in params.getlist('layer'): try: layer = _resolve_layer(request, layer_name) except ObjectDoesNotExist: # bad layer, skip continue if not request.user.has_perm( 'view_resourcebase', obj=layer.get_self_resource()): # invisible layer, skip inclusion continue layer_bbox = layer.bbox # assert False, str(layer_bbox) if bbox is None: bbox = list(layer_bbox[0:4]) else: bbox[0] = min(bbox[0], layer_bbox[0]) bbox[1] = min(bbox[1], layer_bbox[1]) bbox[2] = max(bbox[2], layer_bbox[2]) bbox[3] = max(bbox[3], layer_bbox[3]) config = layer.attribute_config() # Add required parameters for GXP lazy-loading config["title"] = layer.title config["queryable"] = True config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') config["bbox"] = bbox if config["srs"] != 'EPSG:3857' \ else llbbox_to_mercator( [float(coord) for coord in bbox]) if layer.storeType == "remoteStore": service = layer.remote_service # Probably not a good idea to send the access token to every remote service. # This should never match, so no access token should be sent to remote services. ogc_server_url = urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc service_url = urlsplit(service.base_url).netloc if access_token and ogc_server_url == service_url and \ 'access_token' not in service.base_url: url = '%s?access_token=%s' % (service.base_url, access_token) else: url = service.base_url map_layers = MapLayer(map=map_obj, name=layer.typename, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True, source_params=json.dumps({ "ptype": service.ptype, "remote": True, "url": url, "name": service.name, "title": "[R] %s" % service.title })) else: ogc_server_url = urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc layer_url = urlsplit(layer.ows_url).netloc if access_token and ogc_server_url == layer_url and \ 'access_token' not in layer.ows_url: url = layer.ows_url + '?access_token=' + \ access_token else: url = layer.ows_url map_layers = MapLayer( map=map_obj, name=layer.typename, ows_url=url, # use DjangoJSONEncoder to handle Decimal values layer_params=json.dumps(config, cls=DjangoJSONEncoder), visibility=True) if bbox and len(bbox) >= 4: minx, miny, maxx, maxy = [float(coord) for coord in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') == "EPSG:4326": center = list((x, y)) else: center = list(forward_mercator((x, y))) if center[1] == float('-inf'): center[1] = 0 BBOX_DIFFERENCE_THRESHOLD = 1e-5 # Check if the bbox is invalid valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD if valid_x: width_zoom = math.log(360 / abs(maxx - minx), 2) else: width_zoom = 15 if valid_y: height_zoom = math.log(360 / abs(maxy - miny), 2) else: height_zoom = 15 map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) map_obj.handle_moderated_uploads() config = map_obj.viewer_json(request) config['fromLayer'] = True context = { 'config': json.dumps(config), 'create': True, 'layers': layers, 'map': map_obj, 'map_layers': map_layers, 'preview': getattr(settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'leaflet') } else: # list all required layers layers = Layer.objects.all() context = {'create': True, 'layers': layers} return context
def add_layers_to_map_config(request, map_obj, layer_names, add_base_layers=True): DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request) if 'access_token' in request.session: access_token = request.session['access_token'] else: access_token = None bbox = [] layers = [] for layer_name in layer_names: try: layer = _resolve_layer(request, layer_name) except ObjectDoesNotExist: # bad layer, skip continue if not layer.is_published: # invisible layer, skip inclusion continue if not request.user.has_perm('view_resourcebase', obj=layer.get_self_resource()): # invisible layer, skip inclusion continue layer_bbox = layer.bbox[0:4] bbox = layer_bbox[:] bbox[0] = layer_bbox[0] bbox[1] = layer_bbox[2] bbox[2] = layer_bbox[1] bbox[3] = layer_bbox[3] # assert False, str(layer_bbox) def decimal_encode(bbox): import decimal _bbox = [] for o in [float(coord) for coord in bbox]: if isinstance(o, decimal.Decimal): o = (str(o) for o in [o]) _bbox.append(o) return _bbox def sld_definition(style): from urllib import quote _sld = { "title": style.sld_title or style.name, "legend": { "height": "40", "width": "22", "href": layer.ows_url + "?service=wms&request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=" + quote(layer.service_typename, safe=''), "format": "image/png" }, "name": style.name } return _sld config = layer.attribute_config() if hasattr(layer, 'srid'): config['crs'] = {'type': 'name', 'properties': layer.srid} # Add required parameters for GXP lazy-loading attribution = "%s %s" % ( layer.owner.first_name, layer.owner.last_name ) if layer.owner.first_name or layer.owner.last_name else str( layer.owner) srs = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') srs_srid = int(srs.split(":")[1]) if srs != "EPSG:900913" else 3857 config[ "attribution"] = "<span class='gx-attribution-title'>%s</span>" % attribution config["format"] = getattr(settings, 'DEFAULT_LAYER_FORMAT', 'image/png') config["title"] = layer.title config["wrapDateLine"] = True config["visibility"] = True config["srs"] = srs config["bbox"] = decimal_encode( bbox_to_projection([float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=int(srs.split(":")[1]))[:4]) config["capability"] = { "abstract": layer.abstract, "name": layer.alternate, "title": layer.title, "queryable": True, "bbox": { layer.srid: { "srs": layer.srid, "bbox": decimal_encode(bbox) }, srs: { "srs": srs, "bbox": decimal_encode( bbox_to_projection( [float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=srs_srid)[:4]) }, "EPSG:4326": { "srs": "EPSG:4326", "bbox": decimal_encode(bbox) if layer.srid == 'EPSG:4326' else decimal_encode( bbox_to_projection( [float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=4326)[:4]) }, "EPSG:900913": { "srs": "EPSG:900913", "bbox": decimal_encode(bbox) if layer.srid == 'EPSG:900913' else decimal_encode( bbox_to_projection( [float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=3857)[:4]) } }, "srs": { srs: True }, "formats": [ "image/png", "application/atom xml", "application/atom+xml", "application/json;type=utfgrid", "application/openlayers", "application/pdf", "application/rss xml", "application/rss+xml", "application/vnd.google-earth.kml", "application/vnd.google-earth.kml xml", "application/vnd.google-earth.kml+xml", "application/vnd.google-earth.kml+xml;mode=networklink", "application/vnd.google-earth.kmz", "application/vnd.google-earth.kmz xml", "application/vnd.google-earth.kmz+xml", "application/vnd.google-earth.kmz;mode=networklink", "atom", "image/geotiff", "image/geotiff8", "image/gif", "image/gif;subtype=animated", "image/jpeg", "image/png8", "image/png; mode=8bit", "image/svg", "image/svg xml", "image/svg+xml", "image/tiff", "image/tiff8", "image/vnd.jpeg-png", "kml", "kmz", "openlayers", "rss", "text/html; subtype=openlayers", "utfgrid" ], "attribution": { "title": attribution }, "infoFormats": [ "text/plain", "application/vnd.ogc.gml", "text/xml", "application/vnd.ogc.gml/3.1.1", "text/xml; subtype=gml/3.1.1", "text/html", "application/json" ], "styles": [sld_definition(s) for s in layer.styles.all()], "prefix": layer.alternate.split(":")[0] if ":" in layer.alternate else "", "keywords": [k.name for k in layer.keywords.all()] if layer.keywords else [], "llbbox": decimal_encode(bbox) if layer.srid == 'EPSG:4326' else decimal_encode( bbox_to_projection([float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=4326)[:4]) } if layer.storeType == "remoteStore": service = layer.remote_service source_params = { "ptype": service.ptype, "remote": True, "url": service.service_url, "name": service.name, "title": "[R] %s" % service.title } maplayer = MapLayer(map=map_obj, name=layer.alternate, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True, source_params=json.dumps(source_params)) else: ogc_server_url = urlparse.urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc layer_url = urlparse.urlsplit(layer.ows_url).netloc if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url: url = layer.ows_url + '?access_token=' + access_token else: url = layer.ows_url maplayer = MapLayer( map=map_obj, name=layer.alternate, ows_url=url, # use DjangoJSONEncoder to handle Decimal values layer_params=json.dumps(config, cls=DjangoJSONEncoder), visibility=True) layers.append(maplayer) if bbox is not None: minx, maxx, miny, maxy = [float(coord) for coord in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') == "EPSG:4326": center = list((x, y)) else: center = list(forward_mercator((x, y))) if center[1] == float('-inf'): center[1] = 0 BBOX_DIFFERENCE_THRESHOLD = 1e-5 # Check if the bbox is invalid valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD if valid_x: width_zoom = math.log(360 / abs(maxx - minx), 2) else: width_zoom = 15 if valid_y: height_zoom = math.log(360 / abs(maxy - miny), 2) else: height_zoom = 15 map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) map_obj.handle_moderated_uploads() if add_base_layers: layers_to_add = DEFAULT_BASE_LAYERS + layers else: layers_to_add = layers config = map_obj.viewer_json(request.user, access_token, *layers_to_add) config['fromLayer'] = True return config
def new_map_config(request): ''' View that creates a new map. If the query argument 'copy' is given, the initial map is a copy of the map with the id specified, otherwise the default map configuration is used. If copy is specified and the map specified does not exist a 404 is returned. ''' DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config() if request.method == 'GET' and 'copy' in request.GET: mapid = request.GET['copy'] map_obj = _resolve_map(request, mapid, 'base.view_resourcebase') map_obj.abstract = DEFAULT_ABSTRACT map_obj.title = DEFAULT_TITLE if request.user.is_authenticated(): map_obj.owner = request.user config = map_obj.viewer_json(request.user) del config['id'] else: if request.method == 'GET': params = request.GET elif request.method == 'POST': params = request.POST else: return HttpResponse(status=405) if 'layer' in params: bbox = None map_obj = Map( projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')) layers = [] for layer_name in params.getlist('layer'): try: layer = _resolve_layer(request, layer_name) except ObjectDoesNotExist: # bad layer, skip continue if not request.user.has_perm('view_resourcebase', obj=layer.get_self_resource()): # invisible layer, skip inclusion continue layer_bbox = layer.bbox # assert False, str(layer_bbox) if bbox is None: bbox = list(layer_bbox[0:4]) else: bbox[0] = min(bbox[0], layer_bbox[0]) bbox[1] = max(bbox[1], layer_bbox[1]) bbox[2] = min(bbox[2], layer_bbox[2]) bbox[3] = max(bbox[3], layer_bbox[3]) config = layer.attribute_config() # Add required parameters for GXP lazy-loading config["title"] = layer.title config["queryable"] = True config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \ else llbbox_to_mercator([float(coord) for coord in bbox]) if layer.storeType == "remoteStore": service = layer.service maplayer = MapLayer(map=map_obj, name=layer.typename, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True, source_params=json.dumps({ "ptype": service.ptype, "remote": True, "url": service.base_url, "name": service.name })) else: maplayer = MapLayer(map=map_obj, name=layer.typename, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True) layers.append(maplayer) if bbox is not None: minx, miny, maxx, maxy = [float(c) for c in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') == "EPSG:4326": center = list((x, y)) else: center = list(forward_mercator((x, y))) if center[1] == float('-inf'): center[1] = 0 BBOX_DIFFERENCE_THRESHOLD = 1e-5 # Check if the bbox is invalid valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD if valid_x: width_zoom = math.log(360 / abs(maxx - minx), 2) else: width_zoom = 15 if valid_y: height_zoom = math.log(360 / abs(maxy - miny), 2) else: height_zoom = 15 map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) config = map_obj.viewer_json(request.user, *(DEFAULT_BASE_LAYERS + layers)) config['fromLayer'] = True else: config = DEFAULT_MAP_CONFIG return json.dumps(config)
def add_layers_to_map_config(request, map_obj, layer_names, add_base_layers=True): DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request) bbox = [] layers = [] for layer_name in layer_names: try: layer = _resolve_layer(request, layer_name) except ObjectDoesNotExist: # bad layer, skip continue except Http404: # can't find the layer, skip it. continue if not request.user.has_perm('view_resourcebase', obj=layer.get_self_resource()): # invisible layer, skip inclusion continue layer_bbox = layer.bbox[0:4] bbox = layer_bbox[:] bbox[0] = layer_bbox[0] bbox[1] = layer_bbox[2] bbox[2] = layer_bbox[1] bbox[3] = layer_bbox[3] # assert False, str(layer_bbox) def decimal_encode(bbox): import decimal _bbox = [] for o in [float(coord) for coord in bbox]: if isinstance(o, decimal.Decimal): o = (str(o) for o in [o]) _bbox.append(o) # Must be in the form : [x0, x1, y0, y1 return [_bbox[0], _bbox[2], _bbox[1], _bbox[3]] def sld_definition(style): _sld = { "title": style.sld_title or style.name, "legend": { "height": "40", "width": "22", "href": layer.ows_url + "?service=wms&request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=" + quote(layer.service_typename, safe=''), "format": "image/png" }, "name": style.name } return _sld config = layer.attribute_config() if hasattr(layer, 'srid'): config['crs'] = {'type': 'name', 'properties': layer.srid} # Add required parameters for GXP lazy-loading attribution = "%s %s" % ( layer.owner.first_name, layer.owner.last_name ) if layer.owner.first_name or layer.owner.last_name else str( layer.owner) srs = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') srs_srid = int(srs.split(":")[1]) if srs != "EPSG:900913" else 3857 config[ "attribution"] = "<span class='gx-attribution-title'>%s</span>" % attribution config["format"] = getattr(settings, 'DEFAULT_LAYER_FORMAT', 'image/png') config["title"] = layer.title config["wrapDateLine"] = True config["visibility"] = True config["srs"] = srs config["bbox"] = decimal_encode( bbox_to_projection([float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=int(srs.split(":")[1]))[:4]) config["capability"] = { "abstract": layer.abstract, "store": layer.store, "name": layer.alternate, "title": layer.title, "queryable": True, "storeType": layer.storeType, "bbox": { layer.srid: { "srs": layer.srid, "bbox": decimal_encode(bbox) }, srs: { "srs": srs, "bbox": decimal_encode( bbox_to_projection( [float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=srs_srid)[:4]) }, "EPSG:4326": { "srs": "EPSG:4326", "bbox": decimal_encode(bbox) if layer.srid == 'EPSG:4326' else bbox_to_projection([float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=4326)[:4] }, "EPSG:900913": { "srs": "EPSG:900913", "bbox": decimal_encode(bbox) if layer.srid == 'EPSG:900913' else bbox_to_projection([float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=3857)[:4] } }, "srs": { srs: True }, "formats": [ "image/png", "application/atom xml", "application/atom+xml", "application/json;type=utfgrid", "application/openlayers", "application/pdf", "application/rss xml", "application/rss+xml", "application/vnd.google-earth.kml", "application/vnd.google-earth.kml xml", "application/vnd.google-earth.kml+xml", "application/vnd.google-earth.kml+xml;mode=networklink", "application/vnd.google-earth.kmz", "application/vnd.google-earth.kmz xml", "application/vnd.google-earth.kmz+xml", "application/vnd.google-earth.kmz;mode=networklink", "atom", "image/geotiff", "image/geotiff8", "image/gif", "image/gif;subtype=animated", "image/jpeg", "image/png8", "image/png; mode=8bit", "image/svg", "image/svg xml", "image/svg+xml", "image/tiff", "image/tiff8", "image/vnd.jpeg-png", "kml", "kmz", "openlayers", "rss", "text/html; subtype=openlayers", "utfgrid" ], "attribution": { "title": attribution }, "infoFormats": [ "text/plain", "application/vnd.ogc.gml", "text/xml", "application/vnd.ogc.gml/3.1.1", "text/xml; subtype=gml/3.1.1", "text/html", "application/json" ], "styles": [sld_definition(s) for s in layer.styles.all()], "prefix": layer.alternate.split(":")[0] if ":" in layer.alternate else "", "keywords": [k.name for k in layer.keywords.all()] if layer.keywords else [], "llbbox": decimal_encode(bbox) if layer.srid == 'EPSG:4326' else bbox_to_projection([float(coord) for coord in layer_bbox] + [ layer.srid, ], target_srid=4326)[:4] } all_times = None if check_ogc_backend(geoserver.BACKEND_PACKAGE): if layer.has_time: from geonode.geoserver.views import get_capabilities workspace, layername = layer.alternate.split( ":") if ":" in layer.alternate else (None, layer.alternate) # WARNING Please make sure to have enabled DJANGO CACHE as per # https://docs.djangoproject.com/en/2.0/topics/cache/#filesystem-caching wms_capabilities_resp = get_capabilities(request, layer.id, tolerant=True) if wms_capabilities_resp.status_code >= 200 and wms_capabilities_resp.status_code < 400: wms_capabilities = wms_capabilities_resp.getvalue() if wms_capabilities: from defusedxml import lxml as dlxml namespaces = { 'wms': 'http://www.opengis.net/wms', 'xlink': 'http://www.w3.org/1999/xlink', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance' } e = dlxml.fromstring(wms_capabilities) for atype in e.findall( "./[wms:Name='%s']/wms:Dimension[@name='time']" % (layer.alternate), namespaces): dim_name = atype.get('name') if dim_name: dim_name = str(dim_name).lower() if dim_name == 'time': dim_values = atype.text if dim_values: all_times = dim_values.split(",") break if all_times: config["capability"]["dimensions"] = { "time": { "name": "time", "units": "ISO8601", "unitsymbol": None, "nearestVal": False, "multipleVal": False, "current": False, "default": "current", "values": all_times } } if layer.storeType == "remoteStore": service = layer.remote_service source_params = {} if service.type in ('REST_MAP', 'REST_IMG'): source_params = { "ptype": service.ptype, "remote": True, "url": service.service_url, "name": service.name, "title": "[R] %s" % service.title } maplayer = MapLayer(map=map_obj, name=layer.alternate, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True, source_params=json.dumps(source_params)) else: ogc_server_url = urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc layer_url = urlsplit(layer.ows_url).netloc access_token = request.session[ 'access_token'] if request and 'access_token' in request.session else None if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url: url = '%s?access_token=%s' % (layer.ows_url, access_token) else: url = layer.ows_url maplayer = MapLayer( map=map_obj, name=layer.alternate, ows_url=url, # use DjangoJSONEncoder to handle Decimal values layer_params=json.dumps(config, cls=DjangoJSONEncoder), visibility=True) layers.append(maplayer) if bbox and len(bbox) >= 4: minx, maxx, miny, maxy = [float(coord) for coord in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') == "EPSG:4326": center = list((x, y)) else: center = list(forward_mercator((x, y))) if center[1] == float('-inf'): center[1] = 0 BBOX_DIFFERENCE_THRESHOLD = 1e-5 # Check if the bbox is invalid valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD if valid_x: width_zoom = math.log(360 / abs(maxx - minx), 2) else: width_zoom = 15 if valid_y: height_zoom = math.log(360 / abs(maxy - miny), 2) else: height_zoom = 15 map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) map_obj.handle_moderated_uploads() if add_base_layers: layers_to_add = DEFAULT_BASE_LAYERS + layers else: layers_to_add = layers config = map_obj.viewer_json(request, *layers_to_add) config['fromLayer'] = True return config
def new_map_config(request): ''' View that creates a new map. If the query argument 'copy' is given, the initial map is a copy of the map with the id specified, otherwise the default map configuration is used. If copy is specified and the map specified does not exist a 404 is returned. ''' # 3 cases in this function # 1. copy a map # 2. a new map with one or more layers # 3. a new map with no layers DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request) if 'access_token' in request.session: access_token = request.session['access_token'] else: access_token = None # TODO support map copy if request.method == 'GET' and 'copy' in request.GET: mapid = request.GET['copy'] map_obj = _resolve_map(request, mapid, 'base.view_resourcebase') map_obj.abstract = DEFAULT_ABSTRACT map_obj.title = DEFAULT_TITLE if request.user.is_authenticated(): map_obj.owner = request.user config = map_obj.viewer_json(request.user, access_token) del config['id'] else: if request.method == 'GET': params = request.GET elif request.method == 'POST': params = request.POST else: return HttpResponse(status=405) # a new map with a layer if 'layer' in params: bbox = None map_obj = Map( projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')) layers = [] for layer_name in params.getlist('layer'): try: layer = _resolve_layer(request, layer_name) except ObjectDoesNotExist: # bad layer, skip continue if not request.user.has_perm('view_resourcebase', obj=layer.get_self_resource()): # invisible layer, skip inclusion continue layer_bbox = layer.bbox # assert False, str(layer_bbox) if bbox is None: bbox = list(layer_bbox[0:4]) else: bbox[0] = min(bbox[0], layer_bbox[0]) bbox[1] = max(bbox[1], layer_bbox[1]) bbox[2] = min(bbox[2], layer_bbox[2]) bbox[3] = max(bbox[3], layer_bbox[3]) config = layer.attribute_config() # Add required parameters for GXP lazy-loading config["title"] = layer.title config["queryable"] = True config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \ else llbbox_to_mercator([float(coord) for coord in bbox]) if layer.storeType == "remoteStore": service = layer.service # Probably not a good idea to send the access token to every remote service. # This should never match, so no access token should be sent to remote services. ogc_server_url = urlparse.urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc service_url = urlparse.urlsplit(service.base_url).netloc if access_token and ogc_server_url == service_url and 'access_token' not in service.base_url: url = service.base_url + '?access_token=' + access_token else: url = service.base_url maplayer = MapLayer(map=map_obj, name=layer.typename, ows_url=layer.ows_url, layer_params=json.dumps(config), visibility=True, source_params=json.dumps({ "ptype": service.ptype, "remote": True, "url": url, "name": service.name })) else: ogc_server_url = urlparse.urlsplit( ogc_server_settings.PUBLIC_LOCATION).netloc layer_url = urlparse.urlsplit(layer.ows_url).netloc if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url: url = layer.ows_url + '?access_token=' + access_token else: url = layer.ows_url maplayer = MapLayer( map=map_obj, name=layer.typename, ows_url=url, # use DjangoJSONEncoder to handle Decimal values layer_params=json.dumps(config, cls=DjangoJSONEncoder), visibility=True) layers.append(maplayer) if bbox is not None: minx, miny, maxx, maxy = [float(coord) for coord in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') == "EPSG:4326": center = list((x, y)) else: center = list(forward_mercator((x, y))) if center[1] == float('-inf'): center[1] = 0 BBOX_DIFFERENCE_THRESHOLD = 1e-5 # Check if the bbox is invalid valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD if valid_x: width_zoom = math.log(360 / abs(maxx - minx), 2) else: width_zoom = 15 if valid_y: height_zoom = math.log(360 / abs(maxy - miny), 2) else: height_zoom = 15 map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) config = map_obj.viewer_json(request.user, access_token, *(DEFAULT_BASE_LAYERS + layers)) config['fromLayer'] = True geoexplorer2worldmap(config, map_obj, layers) else: # a new map with no layer config = DEFAULT_MAP_CONFIG geoexplorer2worldmap(config, map_obj) return json.dumps(config)
def new_map_config(request): ''' View that creates a new map. If the query argument 'copy' is given, the initial map is a copy of the map with the id specified, otherwise the default map configuration is used. If copy is specified and the map specified does not exist a 404 is returned. ''' DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config() if request.method == 'GET' and 'copy' in request.GET: mapid = request.GET['copy'] map_obj = _resolve_map(request, mapid, 'maps.view_map') map_obj.abstract = DEFAULT_ABSTRACT map_obj.title = DEFAULT_TITLE if request.user.is_authenticated(): map_obj.owner = request.user config = map_obj.viewer_json() del config['id'] else: if request.method == 'GET': params = request.GET elif request.method == 'POST': params = request.POST else: return HttpResponse(status=405) if 'layer' in params: bbox = None map_obj = Map(projection="EPSG:900913") layers = [] for layer_name in params.getlist('layer'): try: layer = Layer.objects.get(typename=layer_name) except ObjectDoesNotExist: # bad layer, skip continue if not request.user.has_perm('layers.view_layer', obj=layer): # invisible layer, skip inclusion continue layer_bbox = layer.bbox # assert False, str(layer_bbox) if bbox is None: bbox = list(layer_bbox[0:4]) else: bbox[0] = min(bbox[0], layer_bbox[0]) bbox[1] = max(bbox[1], layer_bbox[1]) bbox[2] = min(bbox[2], layer_bbox[2]) bbox[3] = max(bbox[3], layer_bbox[3]) layers.append( MapLayer(map=map_obj, name=layer.typename, ows_url=layer.ows_url(), layer_params=json.dumps(layer.attribute_config()), visibility=True)) if bbox is not None: minx, miny, maxx, maxy = [float(c) for c in bbox] x = (minx + maxx) / 2 y = (miny + maxy) / 2 center = forward_mercator((x, y)) if center[1] == float('-inf'): center[1] = 0 if maxx == minx: width_zoom = 15 else: width_zoom = math.log(360 / (maxx - minx), 2) if maxy == miny: height_zoom = 15 else: height_zoom = math.log(360 / (maxy - miny), 2) map_obj.center_x = center[0] map_obj.center_y = center[1] map_obj.zoom = math.ceil(min(width_zoom, height_zoom)) config = map_obj.viewer_json(*(DEFAULT_BASE_LAYERS + layers)) config['fromLayer'] = True else: config = DEFAULT_MAP_CONFIG return json.dumps(config)