示例#1
0
def set_geoannotation(context, icon):
        try:
            geo = IGeoManager(context)
            style = IGeoCustomFeatureStyle(context)
            image = Image.open(context.getFile().getIterator())
            exif_data = get_exif_data(image)
            lat, lon = get_lat_lon(exif_data)
            timestamp = get_timestamp(exif_data)
        except:
            return None
        if lat and lon and geo.isGeoreferenceable():
            geo.setCoordinates('Point', (lon, lat))
            if icon:
                style.geostyles.data['use_custom_styles']=True
                style.geostyles.data['marker_image'] = icon
                style.geostyles.data['marker_image_size'] = 1.0
                style.geostyles.update(style.geostyles)
            logger.info('annotated %s with lat %f, lon %f' % (context.getId(), lat, lon))
            success = True
        else:
            success = False
            logger.info('Image has no EXIF GPS information')
            timestamp = exif_data.get('DateTimeOriginal')
        if timestamp:
            context.setCreationDate(timestamp)
        return success
示例#2
0
def import_lakes2(self):
    lakes = geojson.load(open(
        'src/iwlearn.project/iwlearn/project/dataimport/missing_lakes.json',
        'r'))
    parent = self.portal_url.getPortalObject()['iw-projects']['basins']['lakes']
    for lake in lakes['features']:
        if lake['properties']['TYPE']=='Lake':
            new_obj_id = idn.normalize(lake['properties']['GLWD_ID'])
            print new_obj_id
            self.portal_types.constructContent('Basin', parent, new_obj_id)
            new_obj=parent[new_obj_id]
            if lake['properties']['LAKE_NAME']:
                new_obj.setTitle(lake['properties']['LAKE_NAME'])
            new_obj.setDescription("Area: %s; Perimeter: %s; Countries: %s" % (
                            lake['properties']['AREA_SKM'],
                            lake['properties']['PERIM_KM'],
                            lake['properties']['COUNTRY'],
                            ))
            new_obj.setBasin_type('Lake')
            color='2c80d3'
            style = IGeoCustomFeatureStyle(new_obj)
            style.geostyles.data['use_custom_styles']=True
            style.geostyles.data['polygoncolor']=color
            style.geostyles.update(style.geostyles)
            geo = IGeoManager(new_obj)
            q = asShape(lake['geometry']).simplify(0.1).__geo_interface__
            geo.setCoordinates(q['type'], q['coordinates'])
 def _create_project_location(self, project, location, project_name, description):
     wftool = getToolByName(self, 'portal_workflow')
     if not hasattr(project, 'maps_graphics'):
         Id ='maps_graphics'
         title='Maps/Graphics'
         description='Maps and Graphics'
         project.invokeFactory( 'Folder', id=Id, title=title, description=description)
         wftool.doActionFor( project['maps_graphics'], 'submit')
     mgfolder = project['maps_graphics']
     if not hasattr(mgfolder, 'project_locations'):
         Id ='project_locations'
         title='Project locations'
         description='Project Locations, Hotspots and Demonstration Sites'
         mgfolder.invokeFactory( 'Folder', id=Id, title=title, description=description)
         locfolder = mgfolder['project_locations']
         locfolder.setLayout('kml-openlayers')
         wftool.doActionFor(locfolder,'submit')
     else:
         locfolder = mgfolder['project_locations']
     if location['geoLocId'] not in locfolder.objectIds():
         Id = location['geoLocId']
         title = location['geoLocName']
         locfolder.invokeFactory('Document', id=Id, title=title, description=project_name)
         obj = locfolder[Id]
         obj.update(text=description)
         lat = float(location['latitude'])
         lon = float(location['longitude'])
         geo = IGeoManager(obj)
         geo.setCoordinates('Point', (lon, lat))
         wftool.doActionFor( obj,  'submit')
示例#4
0
 def get_latlon(self):
     geo = IGeoManager(self.context)
     geom = geo.getCoordinates()
     if geom:
         if geom[0] == 'Point':
             return '<geo:Point geo:lat="%f" geo:long="%f"/>' % (
                 geom[1][1], geom[1][0])
示例#5
0
def import_oceans(self):
    oceans = geojson.load(open(
        'src/iwlearn.project/iwlearn/project/dataimport/oceans.json',
        'r'))
    parent = self.portal_url.getPortalObject()['iw-projects']['basins']['oceans']
    for ocean in oceans['features']:
        mpoly = []
        geom = asShape(ocean['geometry'])
        for g in geom.geoms:
            if g.area > 5:
                mpoly.append(g)
        mp = MultiPolygon(mpoly).simplify(0.2)
        q = mp.__geo_interface__
        new_obj_id = idn.normalize(ocean['properties']['NAME'])
        print new_obj_id
        self.portal_types.constructContent('Basin', parent, new_obj_id)
        new_obj=parent[new_obj_id]
        new_obj.setTitle(ocean['properties']['NAME'])
        new_obj.setBasin_type('Ocean')
        color='aa22ff'
        style = IGeoCustomFeatureStyle(new_obj)
        style.geostyles.data['use_custom_styles']=True
        style.geostyles.data['polygoncolor']=color
        style.geostyles.update(style.geostyles)
        geo = IGeoManager(new_obj)
        geo.setCoordinates(q['type'], q['coordinates'])
    def get_venues(self):
        """This function retrieves all related Venue objects for given Info
        and for each Venue gets the coordinates.

        Return a list of venues which have coordinates set.

        Each element of this list is a dictionary that contains three keys:
        location, title, description
        """
        venues = []
        refs = self.context.venue
        if not refs:
            return venues

        for ref in refs:
            ob = ref.to_object
            geo = IGeoManager(ob, None)
            if geo and geo.isGeoreferenceable():
                geometry, coordinates = geo.getCoordinates()
                if not coordinates or len(coordinates) != 2:
                    continue
                else:
                    longitude, latitude = coordinates
                if geometry == 'Point' and longitude and latitude:
                    venues.append({
                        'title':
                        ob.Title(),
                        'description':
                        DESC_TEMPLATE % ob.Description(),
                        'location':
                        "%r,%r,0.000000" % (longitude, latitude),
                    })

        return venues
    def get_venues(self):
        """This function retrieves all related Venue objects for given Info
        and for each Venue gets the coordinates.

        Return a list of venues which have coordinates set.

        Each element of this list is a dictionary that contains three keys:
        location, title, description
        """
        venues = []
        refs = self.context.venue
        if not refs:
            return venues

        for ref in refs:
            ob = ref.to_object
            geo = IGeoManager(ob, None)
            if geo and geo.isGeoreferenceable():
                geometry, coordinates = geo.getCoordinates()
                if not coordinates or len(coordinates) != 2:
                    continue
                else:
                    longitude, latitude = coordinates
                if geometry == 'Point' and longitude and latitude:
                    venues.append({
                        'title': ob.Title(),
                        'description': DESC_TEMPLATE % ob.Description(),
                        'location': "%r,%r,0.000000" % (longitude, latitude),
                    })

        return venues
示例#8
0
def is_georeferenced(context):
    try:
        geo = IGeoManager(context)
        if geo.isGeoreferenceable():
            if geo.getCoordinates()[0]:
                return True
    except TypeError:
        # catch TypeError: ('Could not adapt', <ATFile ...>, <Interfa...oManager>)
        pass
    return False
示例#9
0
 def layers(self):
     #add basemaps
     layers = super(LegalFWMapLayers, self).layers()
     geo = IGeoManager(self.context)
     if self.context.getField('country').get(self.context):
         layers.append(LegalFWCountryMapLayer(self.context))
     if self.context.getField('basin').get(self.context):
         layers.append(LegalFWBasinMapLayer(self.context))
     if geo.isGeoreferenceable():
         if geo.getCoordinates():
             layers.append(LegalFWMapLayer(self.context))
     return layers
示例#10
0
def convert_kml_to_page(self):
    for brain in self.portal_catalog(portal_type = 'File', path='iwlearn/osm'):
        obj = brain.getObject()
        data = obj.get_data()
        parent = obj.getParentNode()
        if callable(obj.id):
            obj_id = obj.id()
        else:
            obj_id = obj.id
        new_obj_id = obj_id.strip('kml') +'htm'
        try:
            self.portal_types.constructContent('Document', parent, new_obj_id)
        except:
            pass
        new_obj=parent[new_obj_id]
        if parent.id =='lmes':
            color='0000bf'
        elif parent.id =='rivers':
            color='56ffff'
        elif parent.id =='lakes':
            color='2c80d3'
        elif parent.id =='aquifers':
            color='c1742c'
        else:
            color ='00ff00'
        features = None
        try:
            features = extractfeatures_from_file(data)
            title = extract_title(data).strip('.kml')
            text = extract_description(data)
            #print features['MultiPolygon']
            print title
            #print text
        except:
            print 'exception in %s' % brain.getId
            pass
        if new_obj.getText():
            print 'skipping set text for %s' % brain.getId
        else:
            new_obj.setText(sanitize(text))
            new_obj.setTitle(title)
        if features:
            style = IGeoCustomFeatureStyle(new_obj)
            style.geostyles.data['use_custom_styles']=True
            style.geostyles.data['polygoncolor']=color
            style.geostyles.update(style.geostyles)
            geo = IGeoManager(new_obj)
            if features['MultiPolygon']:
                shp = features['MultiPolygon']
                q = shp.simplify(0.2).__geo_interface__
                geo.setCoordinates(q['type'], q['coordinates'])
def annotate_110(self):
    data = csv.DictReader(open('src/iwlearn.project/iwlearn/project/dataimport/110m_admin_0_countries.csv', 'r'))
    for brain in self.portal_catalog(portal_type = 'Folder', path='iwlearn/images/countries/'):
        obj=brain.getObject()
    for d in data:
        #print d['json_4326']
        #print d['admin']
        print d['iso_a2']
        child_id = d['iso_a2'].lower() + '.png'
        q = geojson.loads(d['json_4326'])
        print q
        if d['iso_a2'] != '-99':
            child = obj[child_id]
            geo = IGeoManager(child)
            #geo.setCoordinates(**q)
            geo.setCoordinates(q['type'], q['coordinates'])
            child.setDescription('Population: %s' % d['pop_est'])
示例#12
0
    def _get_markers(self, brain):
        """Return dict of marker details.

        Handle Info objects in special way.
        """
        markers = []
        if brain.portal_type == 'tbfac.Info':
            # get related Venues
            obj = brain.getObject()
            if obj is None:
                return []

            refs = obj.venue
            if not refs:
                return []

            for ref in refs:
                venue = ref.to_object
                geo = IGeoManager(venue, None)
                if geo and geo.isGeoreferenceable():
                    geometry, coordinates = geo.getCoordinates()
                    if not coordinates or len(coordinates) != 2:
                        continue
                    else:
                        longitude, latitude = coordinates
                    if geometry == 'Point' and longitude and latitude:
                        markers.append({
                            'uid': IUUID(venue),
                            'search_uid': brain.UID,
                            'url': brain.getURL(),
                            'title': brain.Title,
                            'tags': brain.Subject or [],
                            'start': brain.start or '',
                            'end': brain.end or '',
                            'geometry': {
                                'style': None,
                                'type': 'Point',
                                'coordinates': (longitude, latitude)
                            },
                            'latitude': latitude,
                            'longitude': longitude,
                        })
        else:
            markers = super(UshahidiMapView, self)._get_markers(brain)

        return markers
示例#13
0
    def _get_markers(self, brain):
        """Return dict of marker details.

        Handle Info objects in special way.
        """
        markers = []
        if brain.portal_type == 'tbfac.Info':
            # get related Venues
            obj = brain.getObject()
            if obj is None:
                return []

            refs = obj.venue
            if not refs:
                return []

            for ref in refs:
                venue = ref.to_object
                geo = IGeoManager(venue, None)
                if geo and geo.isGeoreferenceable():
                    geometry, coordinates = geo.getCoordinates()
                    if not coordinates or len(coordinates) != 2:
                        continue
                    else:
                        longitude, latitude = coordinates
                    if geometry == 'Point' and longitude and latitude:
                        markers.append({
                            'uid': IUUID(venue),
                            'search_uid': brain.UID,
                            'url': brain.getURL(),
                            'title': brain.Title,
                            'tags': brain.Subject or [],
                            'start': brain.start or '',
                            'end': brain.end or '',
                            'geometry': {
                                'style': None,
                                'type': 'Point',
                                'coordinates': (longitude, latitude)},
                            'latitude': latitude,
                            'longitude': longitude,
                        })
        else:
            markers = super(UshahidiMapView, self)._get_markers(brain)

        return markers
    def __init__(self, context, request):
        super(GeoShapeForm, self).__init__(context, request)
        self.geomanager = IGeoManager(self.context)

        portal_url = getToolByName(self.context, "portal_url")
        portal = portal_url.getPortalObject()
        props_tool = getToolByName(portal, "portal_properties")
        site_props = getattr(props_tool, "site_properties")
        self.typesUseViewActionInListings = list(site_props.getProperty("typesUseViewActionInListings"))
    def index_object(self, documentId, obj, threshold=None):
        """index an object, normalizing the indexed value to its bounds

           o Objects which have 'None' as indexed value are *omitted*,
             by design.

        'documentId' is the integer ID of the document.
        'obj' is the object to be indexed.
        """
        returnStatus = 0
        try:
            geoitem=IGeoManager(obj)
        except:
            return 0
        if geoitem.wkt:
            geometry = wkt.loads(geoitem.wkt)
        else:
            geometry = None
        if geoitem.isGeoreferenceable() and geoitem.getCoordinates()[1]:
            newValue = geoitem.wkt
            if newValue is callable:
                newValue = newValue()
            oldValue = self.backward.get(documentId, _marker )

            if newValue is _marker:
                if oldValue is not _marker:
                    self.rtree.delete(documentId, wkt.loads(oldValue).bounds)
                    try:
                        del self.backward[documentId]
                    except ConflictError:
                        raise
                    except:
                        pass
            else:
                if oldValue is not _marker and newValue!=oldValue:
                    self.rtree.delete(documentId, wkt.loads(oldValue).bounds)
                if geometry:
                    self.rtree.add(documentId, geometry.bounds)
                self.backward[documentId] = newValue

            returnStatus = 1

        return returnStatus
示例#16
0
def migrate(self):
    projects = self.portal_catalog(portal_type = 'Project')
    for brain in projects:
        project = brain.getObject()
        geo = IGeoManager(project)
        style = IGeoCustomFeatureStyle(project)
        print project.Title()
        print geo.isGeoreferenceable()
        lat =  project.getLatitude()
        lon = project.getLongitude()
        leadagency = project.getLeadagency()
        la =''
        if leadagency:
            la = leadagency.Title().strip()
        if lat and lon and geo.isGeoreferenceable():
            print lat, lon
            geo.setCoordinates('Point', (lon, lat))
            style.geostyles.data['use_custom_styles']=True
            if la == 'Food and Agricultural Organization (FAO)':
                style.geostyles.data['marker_image'] = 'string:${portal_url}/marker-icon-fao.png'
            elif la == 'United Nations Development Programme (UNDP)':
                style.geostyles.data['marker_image'] = 'string:${portal_url}/marker-icon-undp.png'
            elif la == 'International Bank for Reconstruction and Development (WB)':
                style.geostyles.data['marker_image'] = 'string:${portal_url}/marker-icon-wb.png'
            elif la == 'United Nations Environment Programme (UNEP)':
                style.geostyles.data['marker_image'] = 'string:${portal_url}/marker-icon-unep.png'
            elif la == 'United Nations Office for Project Services (UNOPS)':
                style.geostyles.data['marker_image'] = 'string:${portal_url}/marker-icon-unops.png'
            elif la == 'Inter-American Development Bank (IADB)':
                style.geostyles.data['marker_image'] = 'string:${portal_url}/marker-icon-iabd.png'
            elif la == 'International Fund for Agriculture and Development (IFAD)':
                style.geostyles.data['marker_image'] = 'string:${portal_url}/marker-icon-ifad.png'
            style.geostyles.update(style.geostyles)
    return 'finished setting coordinates'
示例#17
0
def import_giwalmes(self):
    lmes = geojson.load(open(
        'src/iwlearn.project/iwlearn/project/dataimport/add_lmes.json',
        'r'))
    parent = self.portal_url.getPortalObject()['iw-projects']['basins']['lmes']
    for lme in lmes['features']:
        new_obj_id = 'giwalme-id-' + idn.normalize(lme['properties']['GIWALME_ID'])
        self.portal_types.constructContent('Basin', parent, new_obj_id)
        new_obj=parent[new_obj_id]
        print new_obj_id
        new_obj.setTitle(lme['properties']['NAME'] + ' (LME)')
        #new_obj.setDescription("Area: %s; Length: %s" % (
        #                lme['properties']['Shape_Area'],
        #                lme['properties']['Shape_Leng']))
        new_obj.setBasin_type('LME')
        color='0000bf'
        style = IGeoCustomFeatureStyle(new_obj)
        style.geostyles.data['use_custom_styles']=True
        style.geostyles.data['polygoncolor']=color
        style.geostyles.update(style.geostyles)
        geo = IGeoManager(new_obj)
        q = asShape(lme['geometry']).simplify(0.2).__geo_interface__
        geo.setCoordinates(q['type'], q['coordinates'])
示例#18
0
    def make_place(self, brain):
        ob = brain.getObject()
        url = brain.getURL() + '/@@adr_view.html'
        view = cgi.escape(AdrView(ob, self.request)()).encode(
                                    'ascii', 'xmlcharrefreplace')
        params = {'outputType': 'json',
            #'documentURL': url,
            'documentContent': view,
            'documentType': 'text/html',
            'appid': 'pySuZD7V34FHjlmmw72YPBBf4R55MwkhtNCo_c3fR1aQY4wNKsU6YevDnyPSwJ53uu3SlwvPifbaWjUCfMu_umRPPGk-',
            }
        try:
            params = urllib.urlencode(params)
        except:
            logger.error(brain.Title + ': error encoding org')
            return brain.Title + ': Error setting coordinates'
        #try:
        response = urllib2.urlopen(self.url, params)
        #except urllib2.HTTPError, e:
            # Check for for Forbidden HTTP status, which means invalid API key.
       #     if e.code == 403:
       #         return ['Invalid API key.']
       #     return ['error %i' % e.code]

        output = json.loads(response.read())
        try:
            logger.info(brain.Title + ': ' +
                str(output['document']['extents']['center']))
            geo = IGeoManager(ob)
            print geo.isGeoreferenceable()
            lat = float(output['document']['extents']['center']['latitude'])
            lon = float(output['document']['extents']['center']['longitude'])
            geo.setCoordinates('Point', (lon, lat))
            return brain.Title + str(output['document']['extents']['center'])
        except:
            logger.error(brain.Title + ': ' + str(output))
            return brain.Title + ': Error setting coordinates'
示例#19
0
def import_rivers(self):
    rivers = geojson.load(open(
        'src/iwlearn.project/iwlearn/project/dataimport/basins.json',
        'r'))
    parent = self.portal_url.getPortalObject()['iw-projects']['basins']['rivers']
    for river in rivers['features']:
        rnd = str(-random.randrange(100,1000))
        new_obj_id = idn.normalize(river['properties']['BCODE'])
        print new_obj_id
        self.portal_types.constructContent('Basin', parent, new_obj_id)
        new_obj=parent[new_obj_id]
        new_obj.setTitle(river['properties']['CATEGORY'])
        new_obj.setDescription("Area: %s; Length: %s" % (
                        river['properties']['Shape_Area'],
                        river['properties']['Shape_Leng']))
        new_obj.setBasin_type('River')
        color='56ffff'
        style = IGeoCustomFeatureStyle(new_obj)
        style.geostyles.data['use_custom_styles']=True
        style.geostyles.data['polygoncolor']=color
        style.geostyles.update(style.geostyles)
        geo = IGeoManager(new_obj)
        q = asShape(river['geometry']).simplify(0.2).__geo_interface__
        geo.setCoordinates(q['type'], q['coordinates'])
示例#20
0
def import_aquifers(self):
    aquifers = geojson.load(open(
        'src/iwlearn.project/iwlearn/project/dataimport/aquifers.json',
        'r'))
    parent = self.portal_url.getPortalObject()['iw-projects']['basins']['aquifers']
    for aquifer in aquifers['features']:
        ext = idn.normalize(aquifer['properties']['FIRST_ISAR'])
        new_obj_id = idn.normalize(aquifer['properties']['NAME']) + ext
        if new_obj_id in parent:
            mpoly = []
            new_obj=parent[new_obj_id]
            geo = IGeoManager(new_obj)
            add_geom = asShape(aquifer['geometry']).simplify(0.2)
            my_geom = wkt.loads(geo.wkt)
            if my_geom.geom_type == 'MultiPolygon':
                for poly in my_geom.geoms:
                    if poly.contains(add_geom):
                        continue
            elif my_geom.contains(add_geom):
                continue
            elif add_geom.contains(my_geom):
                q = add_geom.__geo_interface__
            else:
                if add_geom.geom_type == 'Polygon':
                    mpoly.append(add_geom)
                elif add_geom.geom_type == 'MultiPolygon':
                    mpoly += list(add_geom.geoms)
                if my_geom.geom_type == 'Polygon':
                    mpoly.append(my_geom)
                elif my_geom.geom_type == 'MultiPolygon':
                    mpoly += list(my_geom.geoms)
                q = MultiPolygon(mpoly).__geo_interface__
            geo.setCoordinates(q['type'], q['coordinates'])
            print new_obj_id, '*'
        else:
            self.portal_types.constructContent('Basin', parent, new_obj_id)
            new_obj=parent[new_obj_id]
            print new_obj_id
            new_obj.setTitle(aquifer['properties']['NAME'])
            new_obj.setDescription("Area: %s; Length: %s" % (
                            aquifer['properties']['Shape_Area'],
                            aquifer['properties']['Shape_Leng']))
            new_obj.setBasin_type('Aquifer')
            color='c1742c'
            style = IGeoCustomFeatureStyle(new_obj)
            style.geostyles.data['use_custom_styles']=True
            style.geostyles.data['polygoncolor']=color
            style.geostyles.update(style.geostyles)
            geo = IGeoManager(new_obj)

            q = asShape(aquifer['geometry']).simplify(0.2).__geo_interface__
            geo.setCoordinates(q['type'], q['coordinates'])
示例#21
0
def import_lmes(self):
    lmes = geojson.load(open(
        'src/iwlearn.project/iwlearn/project/dataimport/lmes.json',
        'r'))
    parent = self.portal_url.getPortalObject()['iw-projects']['basins']['lmes']
    for lme in lmes['features']:
        new_obj_id = idn.normalize(lme['properties']['LME_NAME']) #+ rnd
        if new_obj_id in parent:
            mpoly = []
            new_obj=parent[new_obj_id]
            geo = IGeoManager(new_obj)
            add_geom = asShape(lme['geometry']).simplify(0.2)
            my_geom = wkt.loads(geo.wkt)
            if add_geom.geom_type == 'Polygon':
                mpoly.append(add_geom)
            elif add_geom.geom_type == 'MultiPolygon':
                mpoly += list(add_geom.geoms)
            if my_geom.geom_type == 'Polygon':
                mpoly.append(my_geom)
            elif my_geom.geom_type == 'MultiPolygon':
                mpoly += list(my_geom.geoms)
            q = MultiPolygon(mpoly).__geo_interface__
            geo.setCoordinates(q['type'], q['coordinates'])
            #import ipdb; ipdb.set_trace()
            print new_obj_id, '*'
        else:
            self.portal_types.constructContent('Basin', parent, new_obj_id)
            new_obj=parent[new_obj_id]
            print new_obj_id
            new_obj.setTitle(lme['properties']['LME_NAME'] + ' (LME)')
            new_obj.setDescription("Area: %s; Length: %s" % (
                            lme['properties']['Shape_Area'],
                            lme['properties']['Shape_Leng']))
            new_obj.setBasin_type('LME')
            color='0000bf'
            style = IGeoCustomFeatureStyle(new_obj)
            style.geostyles.data['use_custom_styles']=True
            style.geostyles.data['polygoncolor']=color
            style.geostyles.update(style.geostyles)
            geo = IGeoManager(new_obj)
            q = asShape(lme['geometry']).simplify(0.2).__geo_interface__
            geo.setCoordinates(q['type'], q['coordinates'])
示例#22
0
 def is_geo_referenced(self):
     geo = IGeoManager(self.context)
     if geo.isGeoreferenceable():
         return True
     else:
         return False
示例#23
0
 def apply_coordinates(self, content):
     c = self.coordinates
     if c:
         IGeoManager(content).setCoordinates(c['type'], c['coordinates'])
     else:
         IGeoManager(content).removeCoordinates()
class GeoShapeForm(extensible.ExtensibleForm, form.Form):
    implements(IMapView)
    template = viewpagetemplatefile.ViewPageTemplateFile("geoshapeform.pt")
    form_name = "edit_geometry"
    id = "coordinates-form"
    description = _(u"Specify the geometry for this content")
    fields = field.Fields(IGeoManager).select("wkt")
    mapfields = ["geoshapemap"]

    groups = (CsvGroup, GeoStylesForm)

    message_ok = _(u"Changes saved.")
    message_cancel = _(u"No changes made.")
    message_georeference_removed = _(u"Coordinates removed")
    message_coordinates_null = _(
        u"No coordinate has been set. Please, set "
        "coordinates on the map, fill in the WKT "
        "field or import a CSV file."
    )
    message_error_csv = _(u"CSV File not correct. Verify file format.")
    message_error_wkt = _(u"WKT expression not correct. Verify input.")
    message_error_input = _(u"No valid input given.")

    def __init__(self, context, request):
        super(GeoShapeForm, self).__init__(context, request)
        self.geomanager = IGeoManager(self.context)

        portal_url = getToolByName(self.context, "portal_url")
        portal = portal_url.getPortalObject()
        props_tool = getToolByName(portal, "portal_properties")
        site_props = getattr(props_tool, "site_properties")
        self.typesUseViewActionInListings = list(site_props.getProperty("typesUseViewActionInListings"))

    @property
    def next_url(self):
        # Need to send the user to the view url for certain content types.
        url = self.context.absolute_url()
        if self.context.portal_type in self.typesUseViewActionInListings:
            url += "/view"

        return url

    def redirectAction(self):
        self.request.response.redirect(self.next_url)

    def setStatusMessage(self, message):
        ptool = getToolByName(self.context, "plone_utils")
        ptool.addPortalMessage(message)

    @button.buttonAndHandler(_(u"Save"))
    def handleApply(self, action):  # pylint: disable=W0613
        data, errors = self.extractData()
        if errors:
            return

        # set content geo style
        geostylesgroup = [gr for gr in self.groups if gr.__class__.__name__ == "GeoStylesForm"]
        if geostylesgroup:
            stylemanager = IGeoCustomFeatureStyle(self.context)
            fields = geostylesgroup[0].fields
            stylemanager.setStyles([(i, data[i]) for i in fields])

        csv_group = [gr for gr in self.groups if gr.__class__.__name__ == "CsvGroup"]
        filecsv = csv_group[0].widgets["filecsv"].value

        # we remove coordinates if wkt and filecsv are 'empty'
        message = self.message_ok
        if not data["wkt"] and not filecsv:
            message = self.message_georeference_removed
            self.geomanager.removeCoordinates()
        else:
            ok, message = self.addCoordinates(data, filecsv)
            if not ok:
                self.status = message
                return

        self.setStatusMessage(message)
        self.redirectAction()

    @button.buttonAndHandler(_(u"Cancel"))
    def handleCancel(self, action):  # pylint: disable=W0613
        self.setStatusMessage(self.message_cancel)
        self.redirectAction()

    @button.buttonAndHandler(_(u"Remove georeference"), name="remove-georeference")
    def handleRemoveGeoreference(self, action):
        self.geomanager.removeCoordinates()
        self.setStatusMessage(self.message_georeference_removed)
        self.redirectAction()

    def addCoordinates(self, data, filecsv):
        """ from collective.geo.geographer.README.txt
            Now set the location geometry to type "Point"
            and coordinates 105.08 degrees West,
            40.59 degrees North using setGeoInterface()

            >>> geo.setGeoInterface('Point', (-105.08, 40.59))
        """
        if filecsv:
            filecsv.seek(0)
            coords = self.csv2coordinates(filecsv.read())
            if coords:
                # should probably use dataconvert instead of array indexing
                shape = self.groups[0].widgets["coord_type"].value[0]
                if shape.lower() == "polygon":
                    # Polygon expects an outer hull and a hole.
                    coords = (coords,)
                self.geomanager.setCoordinates(shape, coords)
                return True, self.message_ok
            else:
                return False, self.message_error_csv
        else:
            try:
                geom = self.verifyWkt(data["wkt"]).__geo_interface__
                self.geomanager.setCoordinates(geom["type"], geom["coordinates"])
                return True, self.message_ok
            except:  # ReadingError: is a subclass of generic exception
                return False, self.message_error_wkt
        return False, self.message_error_input

    # Verify the incoming CSV file and read coordinates as per the
    # WGS 1984 reference system (longitude, latitude)
    def verifyCsv(self, filecsv):
        reader = csv.reader(cStringIO.StringIO(str(filecsv)), delimiter=",")
        coords = []
        for row in reader:
            # check for row existence ???
            # are there any problems if the row is empty ???
            if row:
                # verify pairs of values are there
                try:
                    longitude = row[0]
                    latitude = row[1]
                except:
                    return False

                # verify that longitude and latitude are non-empty and non-zero
                if longitude != "" and latitude != "":
                    try:
                        # check for float convertible values
                        coords.append((float(longitude), float(latitude)))
                    except:
                        return False

        return coords

    def csv2coordinates(self, csv_data):
        csv_data = self.verifyCsv(csv_data)
        if csv_data != False:
            return tuple(csv_data)
        return False

    def verifyWkt(self, data):
        try:
            from shapely import wkt

            geom = wkt.loads(data)
        except ImportError:
            from pygeoif.geometry import from_wkt

            geom = from_wkt(data)
        return geom
示例#25
0
    def actionSubmit(self, action, data):
        geo = IGeoManager(self.context)
        url = self.context.absolute_url()
        if data.get('extractfeature'):
            features = extractfeatures_from_file(self.context.get_data())
            if data['extractfeature'] == 1:
                if features['MultiPoint']:
                    geom = self.simplify(features['MultiPoint'],
                        data['simplifyvalue'], data['simplify'])
                    q = geom.__geo_interface__
                    geo.setCoordinates(q['type'], q['coordinates'])

            elif data['extractfeature'] == 2:
                if features['MultiLineString']:
                    geom = self.simplify(features['MultiLineString'],
                                data['simplifyvalue'], data['simplify'])
                    q = geom.__geo_interface__
                    geo.setCoordinates(q['type'], q['coordinates'])

            elif data['extractfeature'] == 3:
                if features['MultiPolygon']:
                    geom = self.simplify(features['MultiPolygon'],
                                data['simplifyvalue'], data['simplify'])
                    q = geom.__geo_interface__
                    geo.setCoordinates(q['type'], q['coordinates'])
            elif data['extractfeature'] == 4:
                if (features['MultiPoint'] or
                features['MultiLineString'] or
                features['MultiPolygon']):
                    geoms =[]
                    if features['MultiPoint']:
                        geoms.append(features['MultiPoint'].envelope)
                    if features['MultiLineString']:
                        geoms.append(features['MultiLineString'].envelope)
                    if features['MultiPolygon']:
                        geoms.append(features['MultiPolygon'].envelope)
                    q = MultiPolygon(geoms).envelope.__geo_interface__
                    geo.setCoordinates(q['type'], q['coordinates'])
            elif data['extractfeature'] == 5:
                if (features['MultiPoint'] or
                features['MultiLineString'] or
                features['MultiPolygon']):
                    geoms =[]
                    if features['MultiPoint']:
                        geoms.append(features['MultiPoint'].convex_hull)
                    if features['MultiLineString']:
                        geoms.append(features['MultiLineString'].convex_hull)
                    if features['MultiPolygon']:
                        geoms.append(features['MultiPolygon'].convex_hull)
                    geom = self.simplify(MultiPolygon(geoms).convex_hull,
                                data['simplifyvalue'], data['simplify'])
                    q = geom.__geo_interface__
                    geo.setCoordinates(q['type'], q['coordinates'])

            self.request.response.redirect(self.context.absolute_url() +
                                            '/@@manage-coordinates')