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


Python googlemaps.GoogleMaps类代码示例

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


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

示例1: lookup

def lookup(request):
	what = (request.POST['what']).lower()
	where = (request.POST['where']).lower()

	api = twython.setup('Basic', username='U_Need', password='')
	gmaps = GoogleMaps()

	mentions = api.getUserMentions(since_id=4698625520)

	a = []

	lat1, lng1 = gmaps.address_to_latlng(where)

	#if is not (api):
	#	render_to_response('need/enter.html')

	for stat in mentions:
		text = (stat["text"]).lower()
		ele = text.split(':')
		lat2 = float(ele[2])
		lng2 = float(ele[3])
		if (text.find(what) != -1) and (in_vic(lat1, lng1, lat2, lng2) == 1):
			actual = gmaps.latlng_to_address(lat2, lng2)
			tweet = ele[1] + " " + actual
			a.append(tweet)

	t = loader.get_template("need/results.html")

	c = Context({'stat': a},)
	return HttpResponse(t.render(c))
开发者ID:saahil,项目名称:U_Need,代码行数:30,代码来源:views.py

示例2: do_post

 def do_post(self):
     address = self.param('address')
     lat = self.param('lat')
     lon = self.param('lon')
     miles = self.request.get('miles', default_value=10)
     max_results = self.request.get('max_results', default_value=10)
     geoPoint = None
     try:
         if address:
             try:
                 gmaps = GoogleMaps(self.enviroment.google_maps_key)   
                 lat, lon = gmaps.address_to_latlng(address)
             except:
                 self.write_error('Cannot get position from address')
                 return
         geoPoint = db.GeoPt(lat, lon)
     except:
         self.write_error('Error validating position')
         return
     
     if geoPoint:
         meters = float(miles) * base.METERS_IN_MILE        
         locations = models.Location.proximity_fetch( models.Location.all(), geoPoint, int(max_results), meters )
         if locations and len(locations) > 0:
             json = []
             for loc in locations:             
                 json.append(loc.to_json_object())
             self.write_success(json)
         else:
             self.write_error("No Locations within %s miles" % miles)
开发者ID:pshirkey,项目名称:dodah,代码行数:30,代码来源:service.py

示例3: test_reverse_geocode

 def test_reverse_geocode(self):
     lat, lng = 40.714224, -73.961452
     gmaps = GoogleMaps(GMAPS_API_KEY)
     results = gmaps.reverse_geocode(lat, lng)
     first = results[0]
     for info in ({'long_name': '285',
                   'short_name': '285',
                   'types': ['street_number']},
                  {'long_name': 'Bedford Ave',
                   'short_name': 'Bedford Ave',
                   'types': ['route']},
                  {'long_name': 'New York',
                   'short_name': 'New York',
                   'types': ['locality', 'political']},
                  {'long_name': '11211',
                   'short_name': '11211',
                   'types': ['postal_code']},
                  {'long_name': 'New York',
                   'short_name': 'NY',
                   'types': ['administrative_area_level_1', 'political']},
                  {'long_name': 'United States',
                   'short_name': 'US',
                   'types': ['country', 'political']}):
         self.assertIn(info, first['address_components'])
     self.assertEqual(first['formatted_address'],
                      '285 Bedford Ave, Brooklyn, NY 11211, USA')
     location = first['geometry']['location']
     self.assertAlmostEquals(location['lat'], lat, 3)
     self.assertAlmostEquals(location['lng'], lng, 3)
开发者ID:Polyconseil,项目名称:py-googlemaps,代码行数:29,代码来源:test_googlemaps.py

示例4: test_geocode

 def test_geocode(self):
     addr = u'1600 amphithéatre mountain view ca'
     gmaps = GoogleMaps(GMAPS_API_KEY)
     results = gmaps.geocode(addr)
     first = results[0]
     for info in ({'long_name': '1600',
                   'short_name': '1600',
                   'types': ['street_number']},
                  {'long_name': 'Amphitheatre Parkway',
                   'short_name': 'Amphitheatre Pkwy',
                   'types': ['route']},
                  {'long_name': 'Mountain View',
                   'short_name': 'Mountain View',
                   'types': ['locality', 'political']},
                  {'long_name': '94043',
                   'short_name': '94043',
                   'types': ['postal_code']},
                  {'long_name': 'Santa Clara County',
                   'short_name': 'Santa Clara County',
                   'types': ['administrative_area_level_2', 'political']},
                  {'long_name': 'California',
                   'short_name': 'CA',
                   'types': ['administrative_area_level_1', 'political']},
                  {'long_name': 'United States',
                   'short_name': 'US',
                   'types': ['country', 'political']}):
         self.assertIn(info, first['address_components'])
     self.assertEqual(first['formatted_address'],
                      '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA')
     location = first['geometry']['location']
     self.assertAlmostEquals(location['lat'], 37.4218281, 3)
     self.assertAlmostEquals(location['lng'], -122.0840696, 3)
开发者ID:Polyconseil,项目名称:py-googlemaps,代码行数:32,代码来源:test_googlemaps.py

示例5: miles

def miles(date):
    if not session.get('logged_in'):
        return redirect(url_for('register'))

    # look for any visits
    g.cursor.execute("SELECT * FROM visits v, destinations d WHERE v.day = %s AND v.dest_id = d.id AND v.user_id = %s ORDER BY v.time ASC", (date, g.user_id))
    visits = g.cursor.fetchall()

    if not visits:
        return jsonify(miles=0)

    gmaps = GoogleMaps(GDATA_API_KEY)

    # look for a cached count of the miles
    last_visit = None
    miles = 0.0
    for visit in visits:
        visit = decode_destination(visit)
        if last_visit is None:
            last_visit = visit
            continue
        g.cursor.execute("SELECT miles FROM miles WHERE start_dest_id = %s AND end_dest_id = %s", (last_visit['dest_id'], visit['dest_id']))
        trip_miles = g.cursor.fetchone()
        if trip_miles:
            miles += float(trip_miles['miles'])
        else:
            directions = gmaps.directions(last_visit['address'], visit['address'])
            trip_meters = directions['Directions']['Distance']['meters']
            trip_miles = int(trip_meters * (1/1609.344))
            miles += trip_miles
            g.cursor.execute("INSERT INTO miles (start_dest_id, end_dest_id, miles) VALUES(%s, %s, %s)", (last_visit['dest_id'], visit['dest_id'], trip_miles))
        last_visit = visit

    return jsonify(miles=miles)
开发者ID:adregner,项目名称:mile-tracker,代码行数:34,代码来源:mile-tracker.py

示例6: get_directions

def get_directions():
    api_key = 'AIzaSyAyspF7tDu4Tv0X23RQDjoCoVewalLRv4Q'
    gmaps = GoogleMaps(api_key)
    start = ",".join(driver_start_latlng())
    end = ",".join(rider_start_latlng())
    start2 = ",".join(rider_end_latlng())
    end2 = ",".join(driver_end_latlng())
    dirs = gmaps.directions(start, end)
    time = dirs['Directions']['Duration']['seconds']
    dist = dirs['Directions']['Distance']['meters']
    route = dirs['Directions']['Routes'][0]
    dirs1 = gmaps.directions(end, start2)
    time1 = dirs1['Directions']['Duration']['seconds']
    dist1 = dirs1['Directions']['Distance']['meters']
    route1 = dirs1['Directions']['Routes'][0]
    dirs2 = gmaps.directions(start2, end2)
    time2 = dirs2['Directions']['Duration']['seconds']
    dist2 = dirs2['Directions']['Distance']['meters']
    route2 = dirs2['Directions']['Routes'][0]
    for step in route['Steps']:
        #print step['Point']['coordinates'][1], step['Point']['coordinates'][0]
        print step['descriptionHtml']
    for step in route1['Steps']:
        #print step['Point']['coordinates'][1], step['Point']['coordinates'][0]
        print step['descriptionHtml']
    for step in route2['Steps']:
       # print step['Point']['coordinates'][1], step['Point']['coordinates'][0]
        print step['descriptionHtml']
开发者ID:cryanperkins,项目名称:PublicCode,代码行数:28,代码来源:Poolryde.py

示例7: index

def index(request):
    """
    Main Page
    """
    if request.method == "POST":
        form = LocationForm(request.POST)
        if form.is_valid():
            
            gmaps = GoogleMaps(GOOGLE_MAPS_API_KEY)
            destination = gmaps.latlng_to_address(form.cleaned_data.get('latitude'), form.cleaned_data.get('longitude'))
            print destination
            destination=parse(destination)
            print destination                        
            y=yql.Public()
            query='select * from google.news where q="'+destination+'"'
            print query
            res=y.execute(query,env='store://datatables.org/alltableswithkeys')
            rows = res.rows
    else:
        form = LocationForm()
        rows = {}

    template = "map/index.html"
    data = { 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY,
             'form': form, 'res':rows }
    return render_to_response(template, data, context_instance=RequestContext(request))
开发者ID:machinelearner,项目名称:django-news,代码行数:26,代码来源:views.py

示例8: post

 def post(self):
     
     models.Difficulty.load()
     
     models.User.get_test_user()
     self.redirect(Index.url)
     
     cat = models.Category(name="Food/Beverage", description="")
     cat.put()
     
     subcat = models.Category(name="Resturant", description="", parent_category=cat)
     subcat.put()
     
     subcat = models.Category(name="Coffee House", description="", parent_category=cat)
     subcat.put()
     
     red = models.Location(owner=self.current_user, location=db.GeoPt(37, -122))
     red.address = "310 SW 3rd Street"
     red.name = "Red Horse"
     red.description = "Red Horse Coffee"
     red.category = subcat
     red.city = "Corvallis"
     red.state = "OR"
     red.zip = "97333"
     red.county = "USER"
     red.phone_number = "(541) 757-3025"
     red.rating = 99
     red.put()
     gmaps = GoogleMaps(self.enviroment.google_maps_key)   
     lat, lng = gmaps.address_to_latlng(red.get_address())
     red.update_location(db.GeoPt(lat, lng))
     red.save()
开发者ID:pshirkey,项目名称:dodah,代码行数:32,代码来源:workspace.py

示例9: distances

def distances(start_address,end_address):
	gmaps = GoogleMaps()
	
	base_url = 'http://maps.googleapis.com/maps/api/directions/json?'
	
	travel_mode='mode=walking'
	
	if start_address==end_address:
		return False
	
	start_lat, start_longt = gmaps.address_to_latlng(start_address+', New York, USA')	#Getting the longtitudes and lattitudes of given addresses
	end_lat, end_longt = gmaps.address_to_latlng(end_address+', New York, USA')
	sensor='sensor=false'
	
	test_url=base_url+'&'+travel_mode+'&'+'origin='+str(start_lat)+','+str(start_longt)+'&destination='+str(end_lat)+','+str(end_longt)+'&'+sensor	#Constructs the url to query google maps for walking directions
	print test_url
	
	result = json.load(urllib.urlopen(test_url)) 
	
	met_distance = result['routes'][0]['legs'][0]['distance']['value']	#obtain the walking distance in km
	print 'Metropolitan distance between ', start_address, 'and', end_address , ' is ',met_distance, 'm'
	
	#calculate the straight line distance (over the surface of the Earth) assuming the Earth is a sphere of radius 6378100m
	dlat = m.radians(end_lat-start_lat)
	dlongt = m.radians(end_longt-start_longt)
	
	a = ((m.sin(dlat/2))*(m.sin(dlat/2)))+(m.cos(m.radians(start_lat)) * m.cos(m.radians(end_lat)) * (m.sin(dlongt/2))*(m.sin(dlongt/2)) )
	c = 2 * m.atan2(m.sqrt(a), m.sqrt(1-a))
	d = 6378100 * c
	print 'Whereas line of flight distance is' , d,'m'
	if d == 0 : return False
	rat = met_distance/d
	if rat < 1 : rat = 1
	return rat
开发者ID:gilk,项目名称:cityplan,代码行数:34,代码来源:test4_NYC.py

示例10: verify_restaurant

def verify_restaurant(start):
	api_key = settings.GOOGLE_MAPS
	geo = GoogleMaps(api_key)
	error = "Unfortunately, we are not yet delivering in your area."
	wrong_addr = False

	for r in Restaurant.objects.all():
		end = r.get_address_string()
		try:
			dirs = geo.directions(start, end)
		except:
			wrong_addr = True
			error = "Please enter a valid address."

		dist = float("inf")

		if not wrong_addr:
			dist = dirs['Directions']['Distance']['meters']

		good_radii = ['LaSalle', 'lasalle', 'laSalle', 'LaSalle', 'Lasalle', 'Morreene']

		start_split = start.split(" ")

		for radius in good_radii:
			if radius in start_split:
				return (True, r)

		if dist < r.max_radius:
			return (True, r)

	return (False, error)
开发者ID:dsethan,项目名称:OverEasy,代码行数:31,代码来源:views.py

示例11: get_location

def get_location(zipcode):
    
    gmaps = GoogleMaps(API_key)

    latlong = gmaps.address_to_latlng(zipcode)

    return latlong
开发者ID:mgermino,项目名称:SMS-Business-Lookup,代码行数:7,代码来源:getlocation.py

示例12: direcs

def direcs(loc1, loc2):
    ret = ""
    gmaps = GoogleMaps()
    
    try:
        directions = gmaps.directions(loc1, loc2)
    except:
        return "At least one invalid address. Please try again."
    
    ret += "Will take about " + directions['Directions']['Duration']['html'] + "\n"
    
    for step in directions['Directions']['Routes'][0]['Steps']:
        if "Destination will be on the" in step['descriptionHtml']:
            idx = step['descriptionHtml'].index("Destination")
            s = step['descriptionHtml'][:idx] + "\n" + step['descriptionHtml'][idx:]
            ret += s
        else:
            ret += step['descriptionHtml'] + "\n"
            
    a = ""
    inBracks = False
    for i in range(len(ret)):
        if ret[i] == "<":
            inBracks = True
        elif ret[i] == ">":
            inBracks = False;
        else:
            if inBracks == False:
                a += ret[i]
    return a
开发者ID:jarjun,项目名称:textfordirections,代码行数:30,代码来源:TextForDirections.py

示例13: add_case

  def add_case( self, case ):
    from googlemaps import GoogleMaps
    from time import sleep

    gmaps = GoogleMaps()

    for casa in case:
      casa['cap'] = int( casa['cap'] )
      sleep( 0.2 ) 
      print "Calcolo latitudine/longitudine"

      ( casa['latitudine'], 
        casa['longitudine'] ) = gmaps.address_to_latlng( "%s %d, %s, %s" % ( 
                                                          casa['indirizzo'], casa['cap'], 
                                                          casa['comune'], casa['provincia'] ) ) 
                                                      

      casa['allegati'] = casa['allegati'].replace(' ',',')

      casa['tipo'] = casa['vendita'].upper()
      del( casa['vendita'] )

      casa['base'] = int( casa['costo'].replace('.','').split(',')[0] )
      del( casa['costo'] )

      self.conn.insert( 'case', casa )
      print
开发者ID:lesion,项目名称:strumenti,代码行数:27,代码来源:scrape.py

示例14: coords_from_address

def coords_from_address(address):
    gmaps = GoogleMaps(settings.GOOGLE_API_KEY)
    try:
        result = gmaps.geocode(value)
        lng, lat = result['Placemark'][0]['Point']['coordinates'][0:2]
        return (lat, lng)
    except:
        raise Exception("Address can't be parsed by google maps")
开发者ID:orzubalsky,项目名称:fantastic-futures,代码行数:8,代码来源:utils.py

示例15: time_to_user_profile

	def time_to_user_profile(self):
		api_key = settings.GOOGLE_MAPS
		gmaps = GoogleMaps(api_key)
		start = self.get_address_string
		stop = self.restaurant.get_address_string
		dirs = gmaps.directions(start, stop)
		time = dirs['Directions']['Duration']['seconds']
		return time
开发者ID:dsethan,项目名称:OverEasy,代码行数:8,代码来源:models.py


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