def import_bounding_box(self, layer): """Get bounding box information from the layer; layer is an instance of owslib.wms.ContentMetaData.""" logger.info("BBOX1: " + repr(layer.boundingBoxWGS84)) logger.info("BBOX2: " + repr(layer.boundingBox)) minx = miny = maxx = maxy = srs = None if layer.boundingBoxWGS84: minx, miny, maxx, maxy = layer.boundingBoxWGS84 srs = 'EPSG:4326' else: minx, miny, maxx, maxy, srs = layer.boundingBox logger.info("SRS: " + srs) if srs == "ESPG:900913": # Yay! pass elif srs == "EPSG:28992": minx, miny = coordinates.rd_to_google(minx, miny) maxx, maxy = coordinates.rd_to_google(maxx, maxy) elif srs == "EPSG:4326": minx, miny = coordinates.wgs84_to_google(minx, miny) maxx, maxy = coordinates.wgs84_to_google(maxx, maxy) else: self.bbox = None return self.bbox = ",".join(str(coord) for coord in (minx, miny, maxx, maxy)) logger.info("RESULT: " + self.bbox)
def extent(self, identifiers=None): "Return the extent in Google projection" north = None south = None east = None west = None wgs0coord_x, wgs0coord_y = coordinates.rd_to_wgs84(0.0, 0.0) for point in self.measurement.points.all(): x = point.location.x y = point.location.y if (abs(x - wgs0coord_x) > EPSILON or abs(y - wgs0coord_y) > EPSILON): if x > east or east is None: east = x if x < west or west is None: west = x if y < south or south is None: south = y if y > north or north is None: north = y if north is None: logger.warn("Data points are all at (0, 0) RD, cannot calculate " "extent!") return west_transformed, north_transformed = coordinates.wgs84_to_google( west, north) east_transformed, south_transformed = coordinates.wgs84_to_google( east, south) return { 'north': north_transformed, 'west': west_transformed, 'south': south_transformed, 'east': east_transformed}
def extent(self, identifiers=None): """ TODO: filter on identifiers. """ cache_key = 'extent:{}:{}:{}'.format(self.jdbc_source_slug, self.filterkey, self.parameterkey) result = cache.get(cache_key) if not result: logger.debug("Started calculating extent") north = None south = None east = None west = None named_locations = self._locations() wgs0coord_x, wgs0coord_y = coordinates.rd_to_wgs84(0.0, 0.0) for named_location in named_locations: x = named_location['longitude'] y = named_location['latitude'] # Ignore rd coordinates (0, 0). if (abs(x - wgs0coord_x) > EPSILON or abs(y - wgs0coord_y) > EPSILON): if x > east or east is None: east = x if x < west or west is None: west = x if y < south or south is None: south = y if y > north or north is None: north = y else: logger.warn("Location (%s, %s) at RD coordinates 0,0", named_location['location'], named_location['locationid']) west_transformed, north_transformed = coordinates.wgs84_to_google( west, north) east_transformed, south_transformed = coordinates.wgs84_to_google( east, south) logger.debug("Finished calculating extent") result = { 'north': north_transformed, 'west': west_transformed, 'south': south_transformed, 'east': east_transformed} cache.set(cache_key, result, 60 * 30) return result
def search(self, google_x, google_y, radius=None): """Return list of dict {'distance': <float>, 'timeserie': <timeserie>} of closest fews point that matches x, y, radius. """ def distance(x1, y1, x2, y2): return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) locations = self.datasource.locations() seen_identifiers = [] result = [] for location in locations: identifier = location.identifier if identifier in seen_identifiers: # We constantly get three identical results. continue seen_identifiers.append(identifier) x, y = coordinates.wgs84_to_google( location.longitude, location.latitude) dist = distance(google_x, google_y, x, y) if dist < radius: result.append( {'distance': dist, 'name': location.description(), 'shortname': location.identifier, 'workspace_item': self.workspace_item, 'identifier': {'identifier': identifier}, 'google_coords': (x, y), 'object': None}) result.sort(key=lambda item: item['distance']) return result[:3] # Max 3.
def search(self, google_x, google_y, radius=None): """Return list of dict {'distance': <float>, 'timeserie': <timeserie>} of closest fews point that matches x, y, radius. """ def distance(x1, y1, x2, y2): return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) named_locations = self._locations() result = [] for named_location in named_locations: x, y = coordinates.wgs84_to_google( named_location['longitude'], named_location['latitude']) dist = distance(google_x, google_y, x, y) if dist < radius: result.append( {'distance': dist, 'name': named_location['location'], 'shortname': named_location['location'], 'workspace_item': self.workspace_item, 'identifier': {'location': named_location['locationid']}, 'google_coords': (x, y), 'object': None}) result.sort(key=lambda item: item['distance']) return result[:3] # Max 3.
def location(self, location, layout=None): # Hack; recently we had bugs relating to this function because # locations were passed in that had non-breaking space characters # ('\xa0') appended to them that caused the location_name not # to be found. This might fix it. location = location.strip() # TODO: do the list -> dict conversion only once dict_locations = {} for named_location in self._locations(): dict_locations[named_location['locationid']] = named_location location_name = dict_locations[location]['location'] identifier = {'location': location} if layout is not None: identifier['layout'] = layout x, y = coordinates.wgs84_to_google( dict_locations[location]['longitude'], dict_locations[location]['latitude']) return { 'name': location_name, 'shortname': dict_locations[location]['location'], 'workspace_item': self.workspace_item, 'identifier': identifier, 'google_coords': (x, y), 'object': None}
def search(self, google_x, google_y, radius=None): """ returns a list of dicts with keys distance, name, shortname, google_coords, workspace_item, identifier """ #from lizard_map.coordinates import google_to_rd #x, y = google_to_rd(google_x, google_y) #pnt = Point(x, y, srid=28992) # 900913 pnt = Point(google_x, google_y, srid=900913) # 900913 #print pnt, radius stickies = self.stickies.filter( geom__distance_lte=(pnt, D(m=radius * 0.5))).distance(pnt ).order_by('distance') if stickies: stickies = [stickies[0]] result = [{'distance': 0.0, 'name': '%s (%s)' % (sticky.tweet, sticky.twitter_name), 'shortname': str(sticky.tweet), 'object': sticky, 'google_coords': wgs84_to_google(sticky.geom.x, sticky.geom.y), 'workspace_item': self.workspace_item, 'identifier': {'sticky_id': sticky.id}, } for sticky in stickies] return result
def location(self, identifier, layout=None): locations = self.datasource.locations() for location in locations: if location.identifier == identifier: break else: return None google_x, google_y = coordinates.wgs84_to_google( location.longitude, location.latitude) identifier_to_return = { 'identifier': identifier } if layout is not None: identifier_to_return['layout'] = layout description = location.description() return { 'google_coords': (google_x, google_y), 'name': description, 'shortname': description, 'workspace_item': self.workspace_item, 'identifier': identifier_to_return, 'object': location }
def location(self, sticky_id, layout=None): """ returns location dict. requires identifier_json """ sticky = get_object_or_404(Sticky, pk=sticky_id) identifier = {'sticky_id': sticky.id} return { 'name': '%s (%s)' % (sticky.title, sticky.reporter), 'shortname': str(sticky.title), 'workspace_item': self.workspace_item, 'identifier': identifier, 'google_coords': wgs84_to_google(sticky.geom.x, sticky.geom.y), 'object': sticky, }
def location(self, sticky_id, layout=None): """ returns location dict. requires identifier_json """ sticky = get_object_or_404(StickyTweet, pk=sticky_id) identifier = {'sticky_id': sticky.id} return { 'name': '%s' % (sticky.twitter_name), 'tweet': str(sticky.tweet), 'media_url': str(sticky.media_url), 'workspace_item': self.workspace_item, 'identifier': identifier, 'google_coords': wgs84_to_google(sticky.geom.x, sticky.geom.y), 'object': sticky, }
def search(self, google_x, google_y, radius=None): """Return list of dict {'distance': <float>, 'timeserie': <timeserie>} of closest fews point that matches x, y, radius. """ def distance(x1, y1, x2, y2): return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) named_locations = self._locations() result = [] for named_location in named_locations: x, y = coordinates.wgs84_to_google( named_location['longitude'], named_location['latitude']) dist = distance(google_x, google_y, x, y) if dist < radius: result.append( {'distance': dist, 'name': self._location_plus_parameter( named_location['location']), 'shortname': named_location['location'], 'workspace_item': self.workspace_item, 'identifier': {'location': named_location['locationid']}, 'google_coords': (x, y), 'object': None}) result.sort(key=lambda item: item['distance']) # Normally, only return the closest three points. But if the closest # location has multiple measurements, return all of them. normal_max_number = 3 if len(result) == 0: return result shortest_distance = result[0]['distance'] closest_results = [item for item in result if item['distance'] == shortest_distance] logger.debug("Found %s results, %s with the same distance as the " "closest one", len(result), len(closest_results)) if len(closest_results) >= normal_max_number: return closest_results return result[:3] # Max 3.
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)
def search(self, google_x, google_y, radius=None): """ returns a list of dicts with keys distance, name, shortname, google_coords, workspace_item, identifier """ #from lizard_map.coordinates import google_to_rd #x, y = google_to_rd(google_x, google_y) #pnt = Point(x, y, srid=28992) # 900913 pnt = Point(google_x, google_y, srid=900913) # 900913 #print pnt, radius stickies = self.stickies.filter( geom__distance_lte=(pnt, D(m=radius * 0.5))).distance(pnt).order_by('distance') if stickies: stickies = [stickies[0]] result = [{ 'distance': 0.0, 'name': '%s (%s)' % (sticky.tweet, sticky.twitter_name), 'shortname': str(sticky.tweet), 'object': sticky, 'google_coords': wgs84_to_google(sticky.geom.x, sticky.geom.y), 'workspace_item': self.workspace_item, 'identifier': { 'sticky_id': sticky.id }, } for sticky in stickies] return result
def search(self, google_x, google_y, radius=None): """Search by coordinates. Return list of dicts for matching items. Assumes that the geometries are stored as wgs84. Note that self.parameter_id must be filled. """ def distance(x1, y1, x2, y2): return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) #x, y = coordinates.google_to_wgs84(google_x, google_y) #pnt = GEOSGeometry(Point(x, y), srid=4326) pnt = GEOSGeometry(Point(google_x, google_y), srid=900913) locations = GeoLocationCache.objects.filter( geometry__distance_lte=(pnt, D(m=radius * 0.3)), parameter__ident=self.parameter_id, module__ident=self.module_id) result = [] for location in locations: location_google_x, location_google_y = coordinates.wgs84_to_google( location.geometry.get_x(), location.geometry.get_y()) dist = distance( google_x, google_y, location_google_x, location_google_y) logger.debug(location.__unicode__()) result.append( {'distance': dist, 'name': location.__unicode__(), 'shortname': location.shortname, 'workspace_item': self.workspace_item, 'identifier': { 'ident': location.ident, 'parameter_id': self.parameter_id}, 'google_coords': (location_google_x, location_google_y)}) return result
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
def google_extent(self): xmin, ymin, xmax, ymax = self.geometry.extent xming, yming = coordinates.wgs84_to_google(xmin, ymin) xmaxg, ymaxg = coordinates.wgs84_to_google(xmax, ymax) return xming, yming, xmaxg, ymaxg