示例#1
0
def new_linked_map(request, smapid, snapshot=None, template='maps/map_view.html'):
    """
    The view that returns the map composer opened to
    the map with the given map ID.
    """
    smap=StaticMap.objects.filter(id=smapid)
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config()
    m = Map()
    user = request.user
    m.owner = user
    m.title = 'GISMap_%s' % smap[0].title
    m.abstract = DEFAULT_ABSTRACT
    m.projection = "EPSG:900913"
    m.zoom = 0
    m.center_x = 0
    m.center_y = 0
    m.save()

    smap.update(linked_map=m.id)

    if snapshot is None:
        config = m.viewer_json(request.user, *DEFAULT_BASE_LAYERS)
    else:
        config = snapshot_config(snapshot, m, request.user)

    return render_to_response(template, RequestContext(request, {
        'config': json.dumps(config),
        'map': m
    }))
示例#2
0
    def test_save_story_draft(self):
        """
        Can save draft story
        """
        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')
        mapstory = MapStory()
        self.assertIsInstance(mapstory, MapStory)
        mapstory.title = "Test story"
        mapstory.owner = user
        mapstory.save()

        testMap = Map()
        testMap.story = mapstory
        testMap.zoom = 3
        testMap.projection = "EPSG:900913"
        testMap.center_x = -7377090.47385893
        testMap.center_y = 3463514.6256579063
        testMap.owner = user
        testMap.save()
示例#3
0
    def test_save_story_draft(self):
        """
        Can save draft story
        """
        user = User.objects.create_user(username='******',
                                 email='*****@*****.**',
                                 password='******')
        mapstory = MapStory()
        self.assertIsInstance(mapstory, MapStory)
        mapstory.title = "Test story"
        mapstory.owner = user
        mapstory.save()

        testMap = Map()
        testMap.story = mapstory
        testMap.zoom = 3
        testMap.projection = "EPSG:900913"
        testMap.center_x = -7377090.47385893
        testMap.center_y = 3463514.6256579063
        testMap.owner = user
        testMap.save()
示例#4
0
文件: views.py 项目: ict4eo/geonode
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="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["srs"] = layer.srid
                config["title"] = layer.title
                config["bbox"] = [
                    float(coord) for coord in bbox] if layer.srid == "EPSG:4326" else llbbox_to_mercator(
                    [
                        float(coord) for coord in bbox])
                config["queryable"] = True

                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

                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 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
示例#6
0
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(request)

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        access_token = None

    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)

        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
        else:
            config = DEFAULT_MAP_CONFIG
    return json.dumps(config)
示例#7
0
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)
示例#8
0
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=ogc_server_settings.public_url + "wms",
                        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)
示例#9
0
def create_from_layer_list(user, layers, title, abstract):

    newmap = Map()
    """Copied from maps.models and fixed
    """
    newmap.owner = user
    newmap.title = title
    newmap.abstract = abstract
    newmap.projection = "EPSG:900913"
    newmap.zoom = 0
    newmap.center_x = 0
    newmap.center_y = 0
    #bbox = None
    index = 0
    incr_bbox = None

    DEFAULT_BASE_LAYERS = settings.MAP_BASELAYERS

    is_published = True
    if settings.RESOURCE_PUBLISHING:
        is_published = False
    newmap.is_published = is_published

    # Save the map in order to create an id in the database
    # used below for the maplayers.
    newmap.save()

    # Add background layers

    for layer in DEFAULT_BASE_LAYERS:
        logger.info("Adding baselayer %r", layer)
        maplayer = layer_from_viewer_config(
            MapLayer,
            layer,
            layer['source'],  # source
            index)
        if not maplayer.group == 'background':
            logger.info("Skipping not base layer %r", layer)
            continue
        if 'name' not in layer or not layer['name']:
            logger.info("Unnamed base layer %r", layer)
            maplayer.name = 'UNNAMED BACKGROUND LAYER'

        maplayer.map = newmap
        maplayer.save()
        index += 1

    # Add local layers

    for layer in layers:
        if not isinstance(layer, Layer):
            try:
                layer = Layer.objects.get(typename=layer)
            except ObjectDoesNotExist:
                raise Exception('Could not find layer with name %s' % layer)

        if not user.has_perm('base.view_resourcebase',
                             obj=layer.resourcebase_ptr):
            # invisible layer, skip inclusion or raise Exception?
            raise Exception(
                'User %s tried to create a map with layer %s without having premissions'
                % (user, layer))

        ### Add required parameters for GXP lazy-loading

        # compute (incremental) bbox
        layer_bbox = layer.bbox
        if incr_bbox is None:
            incr_bbox = list(layer_bbox[0:4])
        else:
            incr_bbox[0] = min(incr_bbox[0], layer_bbox[0])
            incr_bbox[1] = max(incr_bbox[1], layer_bbox[1])
            incr_bbox[2] = min(incr_bbox[2], layer_bbox[2])
            incr_bbox[3] = max(incr_bbox[3], layer_bbox[3])

        config = layer.attribute_config()

        config["title"] = layer.title
        config["queryable"] = True
        config[
            "srs"] = layer.srid if layer.srid != "EPSG:4326" else "EPSG:900913"
        config["bbox"] = llbbox_to_mercator(
            [float(coord) for coord in incr_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
        #)

        MapLayer.objects.create(map=newmap,
                                name=layer.typename,
                                ows_url=layer.ows_url,
                                stack_order=index,
                                visibility=True,
                                layer_params=json.dumps(config))

        index += 1

    # Set bounding box based on all layers extents.
    bbox = newmap.get_bbox_from_layers(newmap.local_layers)

    newmap.set_bounds_from_bbox(bbox)

    newmap.set_missing_info()

    # Save again to persist the zoom and bbox changes and
    # to generate the thumbnail.
    newmap.save()

    return newmap
示例#10
0
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)
示例#11
0
文件: views.py 项目: AlfiyaZi/geonode
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)
示例#12
0
def create_from_layer_list(user, layers, title, abstract):

    newmap = Map()

    """Copied from maps.models and fixed
    """
    newmap.owner = user
    newmap.title = title
    newmap.abstract = abstract
    newmap.projection = "EPSG:900913"
    newmap.zoom = 0
    newmap.center_x = 0
    newmap.center_y = 0
    #bbox = None
    index = 0
    incr_bbox = None

    DEFAULT_BASE_LAYERS = settings.MAP_BASELAYERS

    is_published = True
    if settings.RESOURCE_PUBLISHING:
        is_published = False
    newmap.is_published = is_published

    # Save the map in order to create an id in the database
    # used below for the maplayers.
    newmap.save()

    # Add background layers

    for layer in DEFAULT_BASE_LAYERS:
        logger.info("Adding baselayer %r", layer)
        maplayer = layer_from_viewer_config(MapLayer,
            layer,
            layer['source'],  # source
            index)
        if not maplayer.group == 'background':
            logger.info("Skipping not base layer %r", layer)
            continue
        if 'name' not in layer or not layer['name']:
            logger.info("Unnamed base layer %r", layer)
            maplayer.name = 'UNNAMED BACKGROUND LAYER'

        maplayer.map = newmap
        maplayer.save()
        index += 1

    # Add local layers

    for layer in layers:
        if not isinstance(layer, Layer):
            try:
                layer = Layer.objects.get(typename=layer)
            except ObjectDoesNotExist:
                raise Exception(
                    'Could not find layer with name %s' %
                    layer)

        if not user.has_perm(
                'base.view_resourcebase',
                obj=layer.resourcebase_ptr):
            # invisible layer, skip inclusion or raise Exception?
            raise Exception(
                'User %s tried to create a map with layer %s without having premissions' %
                (user, layer))

        ### Add required parameters for GXP lazy-loading

        # compute (incremental) bbox
        layer_bbox = layer.bbox
        if incr_bbox is None:
            incr_bbox = list(layer_bbox[0:4])
        else:
            incr_bbox[0] = min(incr_bbox[0], layer_bbox[0])
            incr_bbox[1] = max(incr_bbox[1], layer_bbox[1])
            incr_bbox[2] = min(incr_bbox[2], layer_bbox[2])
            incr_bbox[3] = max(incr_bbox[3], layer_bbox[3])

        config = layer.attribute_config()

        config["title"] = layer.title
        config["queryable"] = True
        config["srs"] = layer.srid if layer.srid != "EPSG:4326" else "EPSG:900913"
        config["bbox"] = llbbox_to_mercator([float(coord) for coord in incr_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
            #)

        MapLayer.objects.create(
            map=newmap,
            name=layer.typename,
            ows_url=layer.ows_url,
            stack_order=index,
            visibility=True,
            layer_params=json.dumps(config)
        )

        index += 1

    # Set bounding box based on all layers extents.
    bbox = newmap.get_bbox_from_layers(newmap.local_layers)

    newmap.set_bounds_from_bbox(bbox)

    newmap.set_missing_info()

    # Save again to persist the zoom and bbox changes and
    # to generate the thumbnail.
    newmap.save()

    return newmap
示例#13
0
    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

        snapshot = self.kwargs.get('snapshot')

        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)

            if snapshot is None:
                config = map_obj.viewer_json(request)
            else:
                config = snapshot_config(snapshot, map_obj, 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',
                    '')
            }
            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 = 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 = '%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 = 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
                        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()

                if snapshot is None:
                    config = map_obj.viewer_json(request)
                else:
                    config = snapshot_config(snapshot, map_obj, 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',
                        '')
                }

            else:
                # list all required layers
                layers = Layer.objects.all()
                context = {
                    'create': True,
                    'layers': layers
                }
            return context