我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.gis.geos.GEOSGeometry()。
def assign_brandenburg(self, *args, **options): brandenburg_state = State.objects.get(name='Brandenburg') excel_file = pd.ExcelFile(options['filename']) df = excel_file.parse('Brandenburg') assigned_auths = defaultdict(list) locations = {} for _, row in df.iterrows(): auth = SupervisionAuthority.objects.get(state=brandenburg_state, name=row['name']) locations[auth] = GEOSGeometry('POINT(%f %f)' % (row['lng'], row['lat']), srid=4326) assigned_districts = row[u'Landkreis-Zuständigkeit'].splitlines() for district_name in assigned_districts: districts = District.objects.filter(part_of=brandenburg_state, name=district_name) if len(districts) != 1: print(district_name) print(districts) else: assigned_auths[districts[0]].append(auth) for nursinghome in NursingHome.objects.filter(supervision_authority__isnull=True, state=brandenburg_state): district = District.objects.get(geom__covers=nursinghome.geo) auths = assigned_auths[district] if len(auths) == 1: nursinghome.supervision_authority = auths[0] nursinghome.save() else: min_distance = None best_auth = None for auth, point in locations.items(): if auth not in auths: continue dist = NursingHome.objects.filter(pk=nursinghome.pk ).annotate(distance=Distance('geo', point)) dist = dist[0].distance.m if min_distance is None or dist < min_distance: min_distance = dist best_auth = auth nursinghome.supervision_authority = best_auth nursinghome.save()
def geocode(q): zipresult = zipsearch(q) if zipresult[0] is not None: return zipresult if not settings.MAPZEN_SEARCH_APIKEY: return fallback_geocode(q) search_url = SEARCH_URL.format(apikey=settings.MAPZEN_SEARCH_APIKEY, q=q) response = requests.get(search_url) if response.status_code != 200: return fallback_geocode(q) results = response.json() if len(results['features']) == 0: return fallback_geocode(q) first_feature = results['features'][0] point = GEOSGeometry('POINT(%f %f)' % tuple(first_feature['geometry']['coordinates']), srid=4326) return point, first_feature['properties']['label']
def to_python(self, value): """ Transforms the value to a Geometry object. """ if value in self.empty_values: return None if not isinstance(value, GEOSGeometry): try: value = GEOSGeometry(value) except (GEOSException, ValueError, TypeError): raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom') # Try to set the srid if not value.srid: try: value.srid = self.widget.map_srid except AttributeError: if self.srid: value.srid = self.srid return value
def get_zoom(self, geom): "Returns the optimal Zoom level for the given geometry." # Checking the input type. if not isinstance(geom, GEOSGeometry) or geom.srid != 4326: raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.') # Getting the envelope for the geometry, and its associated width, height # and centroid. env = geom.envelope env_w, env_h = self.get_width_height(env.extent) center = env.centroid for z in range(self._nzoom): # Getting the tile at the zoom level. tile_w, tile_h = self.get_width_height(self.tile(center, z).extent) # When we span more than one tile, this is an approximately good # zoom level. if (env_w > tile_w) or (env_h > tile_h): if z == 0: raise GoogleMapException('Geometry width and height should not exceed that of the Earth.') return z - 1 # Otherwise, we've zoomed in to the max. return self._nzoom - 1
def get_initial(self): #In some parts of the world it is not possible to derive the correct timezone from latlng, so user needs to select it. We can prepopulate with best guess though. geojson = json.dumps(self.request.session['new-notice'].get('location', None)) if geojson: centroid = GEOSGeometry(geojson).centroid tf = TimezoneFinder() timezone_from_location = tf.timezone_at(lng=centroid.x, lat=centroid.y) initial = super(NoticeCreateDatetime, self).get_initial() initial['timezone'] = timezone_from_location try: now = datetime.now(pytz.timezone(timezone_from_location)) initial['starts_at'] = now.date() except UnknownTimeZoneError: pass return initial
def load_neighborhoods(): if Neighborhood.objects.count() > 0: print("The neighborhood data has aleady been loaded, skipping neighborhood loading.") else: script_dir = os.path.dirname(__file__) rel_path = '../management/commands/datafiles/neighborhoods.geojson' abs_file_path = os.path.join(script_dir, rel_path) with open(abs_file_path, mode='r') as infile: data = json.load(infile) for d in data['features']: # print(d['properties']['NAME']) # print(d['properties']['MAPLABEL']) # print(d['geometry']) geom = GEOSGeometry(str(d['geometry'])) neighborhood = Neighborhood( geom=geom, name=d['properties']['NAME'], label=d['properties']['MAPLABEL'], ) neighborhood.save()
def handle(self, *args, **options): with open('dengue_linebot/data/tainan_minarea.json') as file: data = json.load(file) for area in data['features']: try: minarea = MinArea( area_id=area['properties']['VILLAGEID'], area_sn=area['properties']['VILLAGESN'], area_name=area['properties']['VILLAGENAM'], district_name=area['properties']['TOWNNAME'], area=GEOSGeometry(json.dumps(area['geometry'])) ) minarea.save() except IntegrityError: self.stderr.write('data have already been imported') break self.stdout.write('Successfully imported')
def test03_transform_related(self): "Testing the `transform` GeoQuerySet method on related geographic models." # All the transformations are to state plane coordinate systems using # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot). tol = 0 def check_pnt(ref, pnt): self.assertAlmostEqual(ref.x, pnt.x, tol) self.assertAlmostEqual(ref.y, pnt.y, tol) self.assertEqual(ref.srid, pnt.srid) # Each city transformed to the SRID of their state plane coordinate system. transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'), ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'), ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'), ) for name, srid, wkt in transformed: # Doing this implicitly sets `select_related` select the location. # TODO: Fix why this breaks on Oracle. qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point')) check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point)
def get_electoral_wards(drupal_admin_id,local_ward_id): url = SHELTER + 'electoral-ward-data/' + str(drupal_admin_id) response = http.request('GET', url) for n in json.loads(response.data)['nodes']: coordinates = n['node']['shape'].split(',0') lst_coordinates = [] for coordinate in coordinates[:-1]: lst_coordinates.append(list(map(float, coordinate.split(',')))) lst_coordinates = [lst_coordinates] key="Polygon" pnt = GEOSGeometry('{ "type": "'+ key +'" , "coordinates": '+ str(lst_coordinates)+' }') admin_data = AdministrativeWard.objects.get(id=local_ward_id) obj, created = ElectoralWard.objects.update_or_create(name= n['node']['name'],administrative_ward = admin_data ,shape=pnt,extra_info=n['node']['description'], defaults={'name': n['node']['name']}) print created