当前位置: 首页>>代码示例>>Python>>正文


Python pygeocoder.Geocoder类代码示例

本文整理汇总了Python中pygeocoder.Geocoder的典型用法代码示例。如果您正苦于以下问题:Python Geocoder类的具体用法?Python Geocoder怎么用?Python Geocoder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Geocoder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: xwalk_generic

def xwalk_generic(form, advert):
    if not advert:
        advert = models.Advert()

    advert.set_owner(current_user.id)

    if form.category.data:
        advert.set_category(form.category.data)

    advert.set_title(form.title.data)

    if form.description.data:
        advert.set_description(form.description.data)

    if form.condition.data:
        advert.set_condition(form.condition.data)

    if form.price.data:
        advert.set_price(form.price.data)

    if form.location.data:
        advert.set_spot(form.location.data)
        if form.location.data == "home":
            if current_user.location:
                lat, lon = current_user.location
                advert.set_location(lat, lon)
            else:
                raise XWalkException(
                    "We do not have an address for your account. If you wish to use this option, please edit your information under My Account."
                )
        elif form.location.data == "uni":
            mail = current_user.id.split("@")
            domain = mail[-1]
            uni = domain_uni_lookup[domain]["address"]
            results = Geocoder.geocode(uni + ", United Kingdom")
            lat, lng = results[0].coordinates
            advert.set_location(lat, lng)
        elif form.location.data == "postcode":
            results = Geocoder.geocode(form.postcode.data + ", United Kingdom")
            lat, lng = results[0].coordinates
            advert.set_location(lat, lng)

    if form.keywords.data:
        advert.set_keywords(form.keywords.data)

    image = request.files["upload"]
    if image and allowed_file(image.filename):
        image_id = uuid.uuid4().hex
        name = image.filename.split(".")
        extension = name[-1]
        image_name = str(image_id) + "." + extension
        image.save(os.path.join(app.config["IMAGES_FOLDER"], image_name))
        advert.set_image_id(image_name)
    elif image and not allowed_file(image.filename):
        flash("This is not an allowed image type", "error")

    advert.expires_in(app.config.get("ADVERT_TIMEOUT", 604800))
    advert.save()
    advert.refresh()
    return advert
开发者ID:CottageLabs,项目名称:uniboard,代码行数:60,代码来源:advert.py

示例2: coordinate_generator

def coordinate_generator(number_of_points):
    """
    Generate a number of random geographical points and then geocode them.

    :param number_of_points: number of points to generate
    :type number_of_points: int
    :return: list of geographic point tuples

    """

    coordinate_list = []
    counter = 0
    geocoder = Geocoder()

    while counter < number_of_points:
        lat = round(random.uniform(SOUTHERNMOST, NORTHERNMOST), 6)
        lng = round(random.uniform(EASTERNMOST, WESTERNMOST), 6)
        try:
            gcode = geocoder.reverse_geocode(lat, lng)

            if gcode[0].data[0]['formatted_address'][-6:] in ('Canada', 'Mexico'):
                continue
            elif 'unnamed road' in gcode[0].data[0]['formatted_address']:
                continue
            elif 'Unnamed Road' in gcode[0].data[0]['formatted_address']:
                continue
            else:
                counter += 1
                coordinate_list.append((gcode[0].coordinates, gcode[0].formatted_address))
            # output_file.write(fullstring.format(gcode.x, gcode.y, gcode.address))
        except GeocoderError:
            continue
    print 'Finished generating %d coordinate points' % counter
    return coordinate_list
开发者ID:michealbeatty,项目名称:Random-Coords,代码行数:34,代码来源:randomcoords.py

示例3: geoloc

def geoloc(request, entreprise_id=None):
	geocoder=Geocoder()
	try:
		proxy=os.environ['http_proxy']
		geocoder.set_proxy(proxy)
	except KeyError:
		pass
	entreprise = Entreprise.objects.get(pk=entreprise_id)
	adresseComplete = entreprise.adresse_propre+","+entreprise.ville_propre
	#testAdresse = "20 place de la Republique, Montargis"

	try:
		if geocoder.geocode(adresseComplete).valid_address :
			resultat = geocoder.geocode(adresseComplete)
			entreprise.latitude=resultat[0].coordinates[0]
			entreprise.longitude=resultat[0].coordinates[1]
			message = "adresse : "+str(resultat[0].coordinates)
			entreprise.save()
		else:
			message = "adresse non valide"
	except Exception as inst:
		message=inst.args
		
	return render(request, "entreprises/geolocalisation.html", {
		'entreprise': entreprise,
		'afficherAC': adresseComplete,
		'message':message
	})
开发者ID:Thoumou,项目名称:gestion_stage,代码行数:28,代码来源:views.py

示例4: save

	def save(self):
		if not (self.latitude and self.longitude):
			geocoder = geocoders.GoogleV3()
			geocoding_results = None

			if self.address:
				try:
					query = '%(address)s, %(city)s, %(state)s' % self.__dict__
					g = Geocoder()
					if g.geocode(query).valid_address:
						geocoding_results = list(geocoder.geocode(query, exactly_one=False))
     					if geocoding_results:
						place, (latitude, longitude) = geocoding_results[0]
						self.latitude = latitude
						self.longitude = longitude
						super(Location, self).save()
					else:
						self.latitude = 0
						self.longitude = 0
						super(Location, self).save()
						self.delete()
						return 'address'
				except GeocoderError:
					return 'address'
		else:
			super(Location, self).save()
开发者ID:politicrowd,项目名称:politicrowd,代码行数:26,代码来源:models.py

示例5: testCreate

def testCreate(request):
	if request.POST:
		form = suggestTest(request.POST)
		#I think this is where we would set the field for latLon
		#request = request.POST.copy()
		#request.setitem('latLon',latLon)
		if form.is_valid():
			address = form.cleaned_data['street']
			latLon = Geocoder.geocode(address)
			form = form.save(commit=False)
			coords = Geocoder.geocode(address)
			coords = coords[0].coordinates
			lat = coords[0]
			lon = coords[1]
			latLon = str(lat)+","+str(lon)
			form.latLon = latLon
			form.save()
			return HttpResponseRedirect(reverse('playgroundapp_home'))
	else:
		form = suggestTest()
	args = {}
	args.update(csrf(request))

	args['form'] = form
	args['dropdown'] = SchoolDistrict.objects.all()
	return render_to_response('playgroundapp/create_playground.html', args)
开发者ID:josieh,项目名称:playground-finder,代码行数:26,代码来源:views.py

示例6: geolocate

 def geolocate(self):
     """Determines the latitude and longitude of the location."""
     if self.geolocated:
         return self.geolocate_success    
     the_address = self.address_for_geolocation()
     logmessage("Trying to geolocate " + str(the_address))
     from pygeocoder import Geocoder
     google_config = get_config('google')
     if google_config and 'api key' in google_config:
         my_geocoder = Geocoder(api_key=google_config['api key'])
     else:
         my_geocoder = Geocoder()
     results = my_geocoder.geocode(the_address)
     self.geolocated = True
     if len(results):
         self.geolocate_success = True
         self.location.gathered = True
         self.location.known = True
         self.location.latitude = results[0].coordinates[0]
         self.location.longitude = results[0].coordinates[1]
         self.location.description = self.block()
         self.geolocate_response = results.raw
         geo_types = {'administrative_area_level_2': 'county', 'neighborhood': 'neighborhood', 'postal_code': 'zip', 'country': 'country'}
         for geo_type, addr_type in geo_types.iteritems():
             if hasattr(results[0], geo_type) and not hasattr(self, addr_type):
                 logmessage("Setting " + str(addr_type) + " to " + str(getattr(results[0], geo_type)) + " from " + str(geo_type))
                 setattr(self, addr_type, getattr(results[0], geo_type))
             #else:
                 #logmessage("Not setting " + addr_type + " from " + geo_type)
         #logmessage(json.dumps(self.geolocate_response))
     else:
         logmessage("valid not ok: result count was " + str(len(results)))
         self.geolocate_success = False
     return self.geolocate_success
开发者ID:alentrekin,项目名称:docassemble,代码行数:34,代码来源:legal.py

示例7: test_business_auth

    def test_business_auth(self):
        """Test Business API access.

        This query fails on purpose, but we inspect and verify the signed URL is correct."""

        # Create the query parameters to sign. The order matters.
        params_to_sign = OrderedDict()
        params_to_sign['address'] = '1600 amphitheatre mountain view ca'
        params_to_sign['components'] = ''
        params_to_sign['bounds'] = ''
        params_to_sign['region'] = ''
        params_to_sign['language'] = ''
        params_to_sign['sensor'] = 'false'

        request_to_sign = requests.Request(
            'GET',
            url=Geocoder.GEOCODE_QUERY_URL,
            params=params_to_sign,
            headers={
                'User-Agent': Geocoder.USER_AGENT
            })
        client_id = 'gme-businessname'
        crypto_key = 'vNIXE0xscrmjlyV-12Nj_BvUPaw='
        g = Geocoder(client_id=client_id, private_key=crypto_key)
        signed_request = g.add_signature(request_to_sign)
        self.assertRegexpMatches(signed_request.url, r'&signature=[a-zA-Z0-9-=]+$', 'Signature must be at end of URL.')
        self.assertRegexpMatches(signed_request.url, r'&client=gme-businessname', 'URL must containg client id.')
        # Verified against https://m4b-url-signer.appspot.com/
        self.assertRegexpMatches(signed_request.url, r'&signature=7bVsUv6kyRHlG0DBAIhKHfX-96M=', 'Incorrect signature')
开发者ID:aaron11496,项目名称:pygeocoder,代码行数:29,代码来源:test.py

示例8: create_map

def create_map(profiles):
    options = ("no", "don't", "not", u"❌", "sorry", u"🚫", u"✋", "paypal", "pp",
        "negociable", "negotiable", "negoatiating", "negotiate",
        "offer", "deal", "lower")
    kml = simplekml.Kml()
    coords_map = {}
    g = Geocoder()
    for p in profiles:
        location = p["location"]

        # Check if it's just a message and not a location
        if any(o in location for o in options):
            continue

        # We can't hit the API too hard
        time.sleep(6)
        try:
            coords = coords_map[location]
        except KeyError:
            try:
                results = g.geocode(location)
                lat, lng = results.coordinates
                coords = [(lng, lat)]
                coords_map[location] = coords
                pnt = kml.newpoint()
                pnt.style.labelstyle.scale = 2  # Make the text twice as big
                pnt.name =  p["user_name"]
                pnt.coords = coords

                # Save the KML
                kml.save("poshmark.kml")
            except GeocoderError as e:
                print e
开发者ID:tatsuhirosatou,项目名称:poshmark-scraper,代码行数:33,代码来源:stats.py

示例9: geo

def geo(request,city1,city2):
    context = RequestContext(request)

    citydata1=Geocoder.geocode(city1)
    codtuple1=citydata1[0].coordinates
    codtuple1=list(codtuple1)

    citydata2=Geocoder.geocode(city2)
    codtuple2=citydata2[0].coordinates
    codtuple2=list(codtuple2)

    #Calculate Distance
    lat1, lon1 = codtuple1
    lat2, lon2 = codtuple2
    R = 6371 #Earth's Radius in Kms.

    lat_diff_radians = math.radians(lat2-lat1)
    long_diff_radians = math.radians(lon2-lon1)
    #Haversine formula to calculate distance between a pair of cordinates
    a = math.sin(lat_diff_radians/2) * math.sin(long_diff_radians/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(long_diff_radians/2) * math.sin(long_diff_radians/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    distance = R * c
    
    context_dict = {'cood1':codtuple1,'cood2':codtuple2,'distance':distance}
    

    return render_to_response('coods.html',context_dict,context)
开发者ID:ashanker1990,项目名称:Geo_locator-Django-App-,代码行数:27,代码来源:views.py

示例10: geocode

def geocode(address):
    try:
        return Geocoder.geocode(address)[0].coordinates
    except:
        rep = re.match(r"((.+-\d+)|(.+\d+号))", ad).group()
        print('%sのgeocodeが見つかりませんでした。調整します。→%s' % (ad, rep))
        return Geocoder.geocode(rep)[0].coordinates
开发者ID:toriumi0118,项目名称:sandbox,代码行数:7,代码来源:getnumber_from_opendata.py

示例11: get_geocode

 def get_geocode(self):
     ad = self._get_address()
     try:
         return Geocoder.geocode("福岡県" + ad)[0].coordinates
     except:
         rep = re.match(r"((.+-\d+)|(.+\d+号))", ad).group()
         print('%sのgeocodeが見つかりませんでした。調整します。→%s' % (ad, rep))
         return Geocoder.geocode("福岡県" + rep)[0].coordinates
开发者ID:toriumi0118,项目名称:sandbox,代码行数:8,代码来源:office.py

示例12: geocode_address

def geocode_address(address):
    if address.cord is None:
        business_geocoder = Geocoder()
        results = business_geocoder.geocode(address.text)
        address.cord = results
    else:
        results = address.cord
    return Coordinate(results[0].coordinates[0], results[0].coordinates[1])
开发者ID:nephraim,项目名称:e-mission-server,代码行数:8,代码来源:trip_gen.py

示例13: dist_address

def dist_address(addr1, addr2):
    ''' given two address, return distance in miles '''
    result1 = Geocoder.geocode(addr1)
    result2 = Geocoder.geocode(addr2)
    if (result1.count==1)&(result2.count==1): ## if only one valid address
        return dist(result1.coordinates, result2.coordinates) ## dist(coordinate1, coordinate2)
    else:
        print 'Error'
        return None
开发者ID:MacHu-GWU,项目名称:six-demon-bag,代码行数:9,代码来源:tutorial01.py

示例14: validate_location

def validate_location(self):
    g = Geocoder()
    isvalid = False
    try:
        isvalid = g.geocode(self).valid_address
    except:
        raise ValidationError("No address was found.")
    if not isvalid:
        raise ValidationError("Please enter a valid address.")
开发者ID:wangslei,项目名称:cookstarter_mirror,代码行数:9,代码来源:validators.py

示例15: find_Path

def find_Path(MAP, model):
    gmaps = GoogleMaps()
    
    home = raw_input("Enter your starting address: ")
    end =  raw_input("Enter your destination address: ")
    results = Geocoder.geocode(home)
    results2 = Geocoder.geocode(end)
    #results = Geocoder.reverse_geocode(41.96786329,-87.71349889)
    #results2 = Geocoder.reverse_geocode(41.763258, -87.61172601)

    print '---Finding Path from ', results, ' to ', results2

    dirs  = gmaps.directions(results, results2)

    time  = dirs['Directions']['Duration']['seconds']
    dist  = dirs['Directions']['Distance']['meters']
    route = dirs['Directions']['Routes'][0]
    
    PATH = []
    EVALUATION = []
    
    for step in route['Steps']:
        position = (step['Point']['coordinates'][1], step['Point']['coordinates'][0])
        if position in MAP:
            for i in range(4): PATH.append('H')
            PATH.append('no')
        else:
            for i in range(4):PATH.append('L')
            PATH.append('yes')
        
        #PREDICT FOR EACH CITY IN THE INTERMEDIATE STEPS
        with open("predict.arff", "a") as myfile:
            for elem in PATH:
                if elem == 'yes' or elem == 'no': myfile.write(elem)
                else: myfile.write(elem  + ',')
            myfile.write('\n')
        PATH = []

    EVALUATION = model.TestClassifier("predict.arff")
    #mark current place as SAFE since you're already at that location anyways
    EVALUATION[0] = 'yes'
    
    #Print Final Results At this Point
    k = 0
    for step in route['Steps']:
        position = (step['Point']['coordinates'][1], step['Point']['coordinates'][0])
        print step['Point']['coordinates'][1], step['Point']['coordinates'][0] ,  '===========================>SAFE? ', EVALUATION[k]
        print step['descriptionHtml']
        k +=1
    
    #UPDATE THE FILES
    delete("predict.arff")
    filename2 = "predict.arff"
    shutil.copy("predict_start.arff", filename2)
    if os.path.isfile (filename2): print "Have a Safe Journey"
    else: print "#####Problem Here: Error 99. Engineeer Will Fix the Bug ASAP"
开发者ID:cpatchava,项目名称:cs229,代码行数:56,代码来源:path.py


注:本文中的pygeocoder.Geocoder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。