Пример #1
0
    def search(self, google_x, google_y, radius=None):
        if not self._user_has_access(google_x, google_y):
            return []

        lon, lat = coordinates.google_to_wgs84(google_x, google_y)
        rd_x, rd_y = coordinates.google_to_rd(google_x, google_y)

        region = models.Region.find_by_point((lon, lat), user=self._user())
        pixel = projections.coordinate_to_composite_pixel(lon, lat)

        if region is None or pixel is None:
            logger.debug("Region is None or pixel is None.")
            return []

        name = self._grid_name(region.name, pixel)

        return [{
            'distance': 0,
            'name': name,
            'shortname': name,
            'workspace_item': self.workspace_item,
            'identifier': {
                'identifier': pixel,
                'region_name': region.name,
                'google_coords': (google_x, google_y),
            },
            'google_coords': (google_x, google_y),
            'object': None
        }]
Пример #2
0
    def search(self, google_x, google_y, radius=None):
        if not self._user_has_access(google_x, google_y):
            return []

        lon, lat = coordinates.google_to_wgs84(google_x, google_y)
        rd_x, rd_y = coordinates.google_to_rd(google_x, google_y)

        region = models.Region.find_by_point((lon, lat), user=self._user())
        pixel = projections.coordinate_to_composite_pixel(lon, lat)

        if region is None or pixel is None:
            logger.debug("Region is None or pixel is None.")
            return []

        name = self._grid_name(region.name, pixel)

        return [{
            'distance': 0,
            'name': name,
            'shortname': name,
            'workspace_item': self.workspace_item,
            'identifier': {
                'identifier': pixel,
                'region_name': region.name,
                'google_coords': (google_x, google_y),
            },
            'google_coords': (google_x, google_y),
            'object': None
        }]
    def handle(self, *args, **options):
        print('coordinate helper')
        y_coords = [7011298, 7011324+20]
        # West
        #print 'west'
        #x_coords = [800101,800107,800112,800117,800122,800126,800132,800138]
        # East
        print 'east'
        x_coords = [800145,800151,800156,800161,800166,800170,800176,800183]
        names = ['A', 'B', 'C', 'D', 'E', 'F', 'G']


        make_box_coordinates = lambda x1, y1, x2, y2: '%(x1)f,%(y1)f,%(x2)f,%(y1)f,%(x2)f,%(y2)f,%(x1)f,%(y2)f' % {'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2}

        for i in range(len(x_coords)-1):
            x1, y1 = coordinates.google_to_wgs84(x_coords[i], y_coords[0])
            x2, y2 = coordinates.google_to_wgs84(x_coords[i+1], y_coords[1])
            print names[i] + ' ' + make_box_coordinates(x1, y1, x2, y2)
Пример #4
0
    def search(self, x, y, radius=None):
        """Search on x, y and return found objects.

        Name is displayed in mouse hover.

        parameter + config (area) + (scenario) + timestep

        if self.selected_date is present: display value.
        """
        if self.selected_date is None:
            logger.error('There is no self.selected_date.')
            return []
        wgs84_x, wgs84_y = google_to_wgs84(x, y)

        # Is always 0 or 1
        areas = WaterbalanceArea.objects.filter(
            geom__contains=Point(wgs84_x, wgs84_y))

        if not areas:
            return []

        area = areas[0]

        # Add value to the name

        # Find corresponding timeseries for areas, parameter
        ts = self._timeseries(area)

        # Look up value
        if ts:
            selected_date_rounded = datetime.date(
                self.selected_date.year,
                self.selected_date.month, 1)
            try:
                ts_event = (
                    ts.timeseries_events.get(
                        time=selected_date_rounded))
                name = '%s - %s=%.2f' % (
                    area.name, self.parameter, ts_event.value)
            except TimeseriesEvent.DoesNotExist:
                # No value found - do nothing
                return []

        # We can only arrive here when the corresponding area has data.
        return [
            {'distance': 0,
             'name': name,
             'shortname': area.name,
             'workspace_item': self.workspace_item,
             'identifier': {'area_id': area.id},
             'object': area}]
Пример #5
0
    def post(self, request, *args, **kwargs):
        post = request.POST
        message_list = ["result: ", ]
        try:
            google_x = float(post['google_x'])
            google_y = float(post['google_y'])
            c_rd = coordinates.google_to_rd(google_x, google_y)
            message_list.append('Google (%s, %s) = RD (%s, %s)' % (
                    google_x, google_y, c_rd[0], c_rd[1]))
            c_wgs84 = coordinates.google_to_wgs84(google_x, google_y)
            message_list.append('Google (%s, %s) = WGS84 (%s, %s)' % (
                    google_x, google_y, c_wgs84[0], c_wgs84[1]))
        except:
            pass

        try:
            rd_x = float(post['rd_x'])
            rd_y = float(post['rd_y'])
            c_google = coordinates.rd_to_google(rd_x, rd_y)
            message_list.append('RD (%s, %s) = Google (%s, %s)' % (
                    rd_x, rd_y, c_google[0], c_google[1]))
            c_wgs84 = coordinates.rd_to_wgs84(rd_x, rd_y)
            message_list.append('RD (%s, %s) = WGS84 (%s, %s)' % (
                    rd_x, rd_y, c_wgs84[0], c_wgs84[1]))
        except:
            pass

        try:
            wgs84_x = float(post['wgs84_x'])
            wgs84_y = float(post['wgs84_y'])
            c_google = coordinates.wgs84_to_google(wgs84_x, wgs84_y)
            message_list.append('WGS84 (%s, %s) = Google (%s, %s)' % (
                    wgs84_x, wgs84_y, c_google[0], c_google[1]))
            c_rd = coordinates.wgs84_to_rd(wgs84_x, wgs84_y)
            message_list.append('WGS84 (%s, %s) = RD (%s, %s)' % (
                    wgs84_x, wgs84_y, c_rd[0], c_rd[1]))
        except:
            pass

        self.message = '<br/>'.join(message_list)
        return super(ConvertView, self).get(request, *args, **kwargs)
Пример #6
0
    def search(self, google_x, google_y, radius=None):
        lon, lat = coordinates.google_to_wgs84(google_x, google_y)

        region = models.Region.find_by_point((lon, lat))
        pixel = projections.coordinate_to_composite_pixel(lon, lat)

        if region is None or pixel is None:
            logger.debug("Region is None or pixel is None.")
            return []

        name = "{0}, cel ({1} {2})".format(region, *pixel)

        return [
            {
                "distance": 0,
                "name": name,
                "shortname": name,
                "workspace_item": self.workspace_item,
                "identifier": {"identifier": pixel, "region_name": region.name},
                "google_coords": (google_x, google_y),
                "object": None,
            }
        ]
Пример #7
0
    def get_feature_info(self, x=None, y=None, radius=None):
        """Gets feature info from the server, at point (x,y) in Google
        coordinates.

        If x, y aren't given, use this layer's bbox, if any. Useful to
        get available features immediately after fetching the layer.
        """

        if x is not None:
            # Construct the "bounding box", a tiny area around (x,y) We use a
            # tiny custom radius, because otherwise we don't have enough
            # control over which feature is returned, there is no mechanism to
            # choose the feature closest to x, y.
            if radius is not None:
                # Adjust the estimated "radius" of an icon on the map.
                radius /= 50
                # Convert to wgs84, which is the only supported format for
                # pyproj.geodesic
                lon, lat = coordinates.google_to_wgs84(x, y)
                # Translate center coordinates to lower left and upper right.
                # Only supports wgs84.
                # Note: 180 + 45 = 225 = bbox lower left.
                geod_bbox = coordinates.translate_coords(
                    [lon] * 2, [lat] * 2, [225, 45], [radius] * 2)
                # Convert back to web mercator.
                ll = coordinates.wgs84_to_google(geod_bbox[0][0],
                                                 geod_bbox[1][0])
                ur = coordinates.wgs84_to_google(geod_bbox[0][1],
                                                 geod_bbox[1][1])
                # Format should be: minX, minY, maxX, maxY.
                bbox = '{},{},{},{}'.format(ll[0], ll[1], ur[0], ur[1])
            else:
                # Use the old method.
                fixed_radius = 10
                bbox = '{},{},{},{}'.format(x - fixed_radius, y - fixed_radius,
                                            x + fixed_radius, y + fixed_radius)
        else:
            bbox = self.bbox

        if not bbox:
            return set()

        version = '1.1.1'
        if self.connection and self.connection.version:
            version = self.connection.version

        params = json.loads(self.params)
        values = dict()
        for layer in params['layers'].split(","):
            payload = {
                'REQUEST': 'GetFeatureInfo',
                'EXCEPTIONS': 'application/vnd.ogc.se_xml',
                'INFO_FORMAT': 'text/plain',
                'SERVICE': 'WMS',
                'SRS': 'EPSG:3857',  # Always Google (web mercator)

                # Get a single feature
                'FEATURE_COUNT': 1,

                # Set the layer we want
                'LAYERS': layer,
                'QUERY_LAYERS': layer,

                'BBOX': bbox,

                # Get the value at the single pixel of a 1x1 picture
                'HEIGHT': 1,
                'WIDTH': 1,
                'X': 0,
                'Y': 0,

                # Version from parameter
                'VERSION': version,
            }

            r = requests.get(self.url, params=payload)

            # XXX Check result code etc
            if 'no features were found' in r.text:
                continue

            if not r.text.startswith("Results for FeatureType"):
                continue

            # "Parse"
            for line in r.text.split("\n"):
                line = line.strip()
                parts = line.split(" = ")
                if len(parts) != 2:
                    continue
                feature, value = parts

                if value.startswith("[GEOMETRY"):
                    # I think these are always uninteresting
                    continue

                values[feature] = value

        self._store_features(values)
        return values
Пример #8
0
    def search(self, x, y, radius=None):
        """
        """

        pt = Point(coordinates.google_to_rd(x, y), 4326)

        # Looking at how radius is derived in lizard_map.js, it's best applied
        # to the y-coordinate to get a reasonable search distance in meters.

        lon1, lat1 = coordinates.google_to_wgs84(x, y - radius)
        lon2, lat2 = coordinates.google_to_wgs84(x, y + radius)

        # On my computer, a call to Proj() is needed

        pyproj.Proj(init='epsg:4326')

        # before Geod

        geod = pyproj.Geod(ellps='WGS84')

        # Django chrashes with:

        # Rel. 4.7.1, 23 September 2009
        # <(null)>:
        # ellipse setup failure
        # program abnormally terminated

        _forward, _backward, distance = geod.inv(lon1, lat1, lon2, lat2)
        distance /= 2.0

        # Find all profiles within the search distance. Order them by distance.

        results = []

        for location in (Location.objects.
                         filter(project=self.project,
                                the_geom__distance_lte=(pt, D(m=distance))).
                         distance(pt).order_by('distance')):
            if self.measurement_type:
                scheduleds = (ScheduledMeasurement.objects.
                              filter(location=location,
                                     contractor=self.contractor,
                                     measurement_type=self.measurement_type))
            else:
                scheduleds = (ScheduledMeasurement.objects.
                              filter(location=location,
                                     contractor=self.contractor,
                               measurement_type__mtype__can_be_displayed=True).
                              order_by('measurement_type__mtype__name'))

            for scheduled in scheduleds:
                result = {
                    'name': '%s %s %s' % (location.location_code,
                                          scheduled.measurement_type.name,
                                          self.contractor.name),
                    'distance': location.distance.m,
                    'workspace_item': self.workspace_item,
                    'identifier': {
                        'scheduled_measurement_id': scheduled.id,
                        },
                    'grouping_hint': 'lizard_progress %s %s %s %s' % (
                        self.workspace_item.id,
                        self.contractor.slug,
                        self.project.slug,
                        scheduled.measurement_type.slug),
                    }
                results.append(result)
            if results:
                # For now, only show info from one location because
                # our templates don't really work with more yet
                break

        logger.debug("Results=" + str(results))
        return results