Exemplo n.º 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
    }))
Exemplo n.º 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()
Exemplo n.º 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()
Exemplo n.º 4
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)
        map_obj.handle_moderated_uploads()
        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'))

            if request.user.is_authenticated():
                map_obj.owner = request.user
            else:
                map_obj.owner = get_anonymous_user()

            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))

            map_obj.handle_moderated_uploads()
            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)
Exemplo n.º 5
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
Exemplo n.º 6
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
Exemplo n.º 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(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)
        map_obj.handle_moderated_uploads()
        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'))

            if request.user.is_authenticated():
                map_obj.owner = request.user
            else:
                map_obj.owner = get_anonymous_user()

            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))

            map_obj.handle_moderated_uploads()
            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)