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))
def main(argv): """ Geocodes a location given on the command line. Usage: googlemaps.py "1600 amphitheatre mountain view ca" [YOUR_API_KEY] googlemaps.py 37.4219720,-122.0841430 [YOUR_API_KEY] When providing a latitude and longitude on the command line, ensure they are separated by a comma and no space. """ if len(argv) < 2 or len(argv) > 4: print main.__doc__ sys.exit(1) query = argv[1] if len(argv) == 3: api_key = argv[2] else: api_key = raw_input("Google Maps API key: ") gmap = GoogleMaps(api_key) try: result = gmap.geocode(query) except GoogleMapsError, err: sys.stderr.write('%s\n%s\nResponse:\n' % (err.url, err)) json.dump(err.response, sys.stderr, indent=4) sys.exit(1)
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
def create(self, request): """Add a new device location.""" attrs = self.flatten_dict(request.POST) try: device = Device.objects.get(user=request.user, name=attrs['device_name'], mobile_id=attrs['device_id']) except Device.DoesNotExist: return rc.NOT_FOUND gmaps = GoogleMaps() try: address = gmaps.latlng_to_address(float(attrs['lat']), float(attrs['lon'])) except GoogleMapsError: address = None device_location = DeviceLocation(device=device, address=address, lat=float(attrs['lat']), lon=float(attrs['lon']), created=datetime.datetime.now()) device_location.save() return rc.CREATED
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)
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)
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)
def lookup(request): what = (request.POST['what']).lower() where = (request.POST['where']).lower() api = twython.setup('Basic', username='******', 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))
def get_location(zipcode): gmaps = GoogleMaps(API_key) latlong = gmaps.address_to_latlng(zipcode) return latlong
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)
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()
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
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)
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']
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
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
def get_lat_long(self): from googlemaps import GoogleMaps gmaps = GoogleMaps(italian - 1489414695369) Address = self.address lat, lng = gmaps.address_to_latlng(address) self.latitude = lat self.longitude = lng save()
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")
def dist_to_restaurant(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) dist = dirs['Directions']['Distance']['meters'] dist_in_miles = float(dist*.000621371) return dist_in_miles
def getMap(businessid): GOOGLEMAPS_API_KEY = settings.GOOGLEMAPS_API_KEY gmaps = GoogleMaps(GOOGLEMAPS_API_KEY) business = Businesses.objects.filter(businessID = businessid)[0] address = business.street + ' ' + business.city + ' ' + str(business.zipCode) lat, lng = gmaps.address_to_latlng(address) return lat,lng
def _geo_loc(self, cr, uid, ids, field_name, arg, context): result = {} gmaps = GoogleMaps("http://maps.googleapis.com/maps/api/js?key=AIzaSyBwNE-vFDyyOb62ODaRiqpiL2kz8wR0aTc") for partner in self.browse(cr,uid,ids): address = partner.street lat, lng = gmaps.address_to_latlng(address) latlng = str(lat) +","+ str(lng) result[partner.id] = str(latlng) return result
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"
def test_point_from_latlng(self): gmaps = GoogleMaps(settings.GOOGLEMAPS_API_KEY) latlng = gmaps.address_to_latlng(u'Jose javier Diaz 440, cordoba, argentina', ) point=None try: point = MaapPoint(geom=Point(latlng).wkt) point.save() except Exception, e: self.assertIsNotNone(point, msg=e)
def returnCoordinate(tweets): gmaps = GoogleMaps('AIzaSyB8YS_1RgpdLZogrpNsZ6V7Yc6mKJAE_og') updated=[] for tweet in tweets: location=re.search('where:([\w]+)', lower(tweet['text'])) if location: address = location.group(1) lat, lng = gmaps.address_to_latlng(address) updated.append([location, lat, lng]) return updated
def test_directions(self): gmaps = GoogleMaps(GMAPS_API_KEY) origin = 'Constitution Ave NW & 10th St NW, Washington, DC' destination = 'Independence and 6th SW, Washington, DC 20024, USA' results = gmaps.directions(origin, destination, units='metric') leg = results[0]['legs'][0] self.assertIn(leg['duration']['value'], range(300, 400)) self.assertIn(leg['distance']['value'], range(2500, 3000)) self.assertIn('Constitution Ave NW', leg['steps'][0]['html_instructions']) self.assertIn('Independence', leg['steps'][-1]['html_instructions'])
def get_loc(address): api_key = "ABQIAAAA_Nl9CTT83Tx0_6m45f7SQxRfRo7TXTpgZcKZw6sB7U7ZlfQK2BQV36qlGpf3-HF0Ntlqdf8T-Gaqxg" gmaps = GoogleMaps(api_key) lat, lng = gmaps.address_to_latlng(address) print lat, lng return lat, lng
def createMap(self): gmaps = GoogleMaps("ABQIAAAAQQRAsOk3uqvy3Hwwo4CclBTrVPfEE8Ms0qPwyRfPn-DOTlpaLBTvTHRCdf2V6KbzW7PZFYLT8wFD0A") address = self.location lat, lng = gmaps.address_to_latlng(address) m = pymaps.PyMap(lat, lng) m.key = "ABQIAAAAQQRAsOk3uqvy3Hwwo4CclBTrVPfEE8Ms0qPwyRfPn-DOTlpaLBTvTHRCdf2V6KbzW7PZFYLT8wFD0A" m.maps[0].zoom = 17 q = [lat,lng, 'Search Result Location: '+ address] m.maps[0].setpoint(q) open('test.html','wb').write(m.showhtml()) # generate test file webbrowser.open('test.html')
def _geo_loc(self, cr, uid, ids, field_name, arg, context): result = {} gmaps = GoogleMaps( "http://maps.googleapis.com/maps/api/js?key=AIzaSyBwNE-vFDyyOb62ODaRiqpiL2kz8wR0aTc" ) for partner in self.browse(cr, uid, ids): address = partner.street lat, lng = gmaps.address_to_latlng(address) latlng = str(lat) + "," + str(lng) result[partner.id] = str(latlng) return result
def FindPizza(): print "Enter in an address to find Pizza places near it" address = raw_input() gmaps = GoogleMaps("AIzaSyA5R4PnzAcoe2vpVRKyWWby-d6RrMmIwtQ") lat, lng = gmaps.address_to_latlng(address) destination = gmaps.latlng_to_address(lat, lng) Pizza = gmaps.local_search('pizza near ' + destination) directions = gmaps.directions(address, destination) print "The nearest Pizza place is " + Pizza['responseData']['results'][0]['titleNoFormatting'] for step in directions['Directions']['Routes'][0]['Steps']: print step['descriptionHtml']
def get_travel_time_between(self, address1, address2): gmaps = GoogleMaps() try: directions = gmaps.directions(address1, address2) except GoogleMapsError: return None if directions: try: return directions["Directions"]["summaryHtml"] except KeyError: return None
def time_from_coords(src_coords, dst_coords): gmaps = GoogleMaps() src_addr = gmaps.latlng_to_address(*src_coords).encode('utf-8') dst_addr = gmaps.latlng_to_address(*dst_coords).encode('utf-8') dirs = gmaps.directions(src_addr,dst_addr) #returns - distance km, time min dist = dirs.get('Directions',{}).get('Distance',{}).get('html','') duration = dirs.get('Directions',{}).get('Duration',{}).get('html','') return (dist,duration)
def dist_from(destination, location): gmaps = GoogleMaps('ABQIAAAAAPMmDP4HCUrLtqjxnhTeXRQV_yMSNSvbo2tmQzi3qOzMvFrzcRTFTor1bOkU8NE2pW1HDlgjEDlcIQ') try: origin = location destination = '6224 Agricultural Road Vancouver, B.C. CA V6T 1Z1' dirs = gmaps.directions(origin, destination, mode='walking') time = dirs['Directions']['Duration']['html'] dist = dirs['Directions']['Distance']['meters'] route = dirs['Directions']['Routes'][0] return dist except GoogleMapsError: return 10000
def lugarnuevo(request): if request.method == 'POST': formulario = LugarNuevo(request.POST) if formulario.is_valid(): #Obtencion de valores del formulario para generar el XML direccion = formulario.cleaned_data['direccion'] print direccion poblacion = formulario.cleaned_data['poblacion'] print poblacion nombre = formulario.cleaned_data['nombre'] print nombre tipo = formulario.cleaned_data['tipo'] print tipo gmaps = GoogleMaps('AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A') direccion = direccion + ',' + poblacion lat, lng = gmaps.address_to_latlng(direccion) lat = str(lat) lng = str(lng) if tipo == '1': tipo = 'bar' elif tipo == '2': tipo = 'cafeteria' elif tipo == '3': tipo = 'comida' elif tipo == '4': tipo = 'restaurante' print tipo xml = "<PlaceAddRequest>" + "<location>" + "<lat>" + \ lat + \ "</lat>" + "<lng>" + lng + "</lng>" + \ "</location>" + \ "<accuracy>" + "5" + "</accuracy>" + \ "<name>" + nombre + "</name>" + \ "<type>" + tipo + "</type>" + \ "<language>" + "es" + "</language>" + \ "</PlaceAddRequest>" #print xml ##utilizamos request, una libreria mas optimizada que urllib2 #r = requests.post('https://maps.googleapis.com/maps/api/place/ \ #add/xml?sensor=false&key= \ #AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A', xml) #print r.content url = 'https://maps.googleapis.com/maps/api/place/add/xml?sensor=false&key=AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A' req = urllib2.Request(url, xml, headers={'Content-Type': 'application/xml'}) consulta = urllib2.urlopen(req) print consulta.read() else: formulario = LugarNuevo() return render_to_response('lugarnuevo.html', {'formulario': formulario}, context_instance=RequestContext(request))
def select(paras): gmaps = GoogleMaps() address = paras['street'] + ", " + paras['city'] + ", " + paras['state'] latitude, longtitude = gmaps.address_to_latlng(address) print "Location convertion: " + str(latitude) + str(longtitude) time_start_mon = int(paras['s_mon']) time_start_day = int(paras['s_day']) time_start_hour = int(paras['s_hou']) time_end_mon = int(paras['e_mon']) time_end_day = int(paras['e_day']) time_end_hour = int(paras['e_hou']) radius = paras['r'] start_time = datetime.datetime(2012, time_start_mon, time_start_day, time_start_hour, 0) end_time = datetime.datetime(2012, time_end_mon, time_end_day, time_end_hour, 0) start_epoch_time = time.mktime(start_time.timetuple()) * 1000 end_epoch_time = time.mktime(end_time.timetuple()) * 1000 distance = "3959*acos((sin({3}/57.29577951)*sin(latitude/57.29577951)+cos({3}/57.29577951)*cos(latitude/57.29577951)*cos(abs(longtitude-({2}))/57.29577951))) <{4}" querystr = ( "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} and " + distance + " order by user;").format(start_epoch_time, end_epoch_time, longtitude, latitude, radius) if (paras['r'] == '0'): querystr = ( "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} order by user;" ).format(start_epoch_time, end_epoch_time) print querystr con, cur = sql_execute(querystr) data = [] while True: dat = cur.fetchone() if dat == None: break data.append(dat) if (paras['type'] == '0'): return top_k_similar(data, paras['option1'], paras['option2'], paras['deadline']) if (paras['type'] == '1'): return mst.call_mst(data, paras['deadline']) if (paras['type'] == '2'): return kmeans_new.call_kmeans(data, paras['deadline'], int(paras['option1'])) if (paras['type'] == '3'): return represent.call_represent(data, paras['deadline'], int(paras['option1'])) else: return [], [] pass
def layer_flag(layer): if layer: center = get_layer_center(layer) gmaps = GoogleMaps(settings.GOOGLE_API_KEY) lat = center.get('lat',None) lng = center.get('lng', None) if lat and lng: addr = gmaps.latlng_to_address(lat, lng) pieces = addr.split(",") country = pieces[-1].strip() flag_location = country_flag(country) return "<img src='%s'/>" % flag_location return ""
def tweet(request): api = twython.setup('Basic', request.session['username'], request.session['password']) gmaps = GoogleMaps() what = request.POST['what'] where = request.POST['where'] lat, lng = gmaps.address_to_latlng(where) tweet = "@U_Need :" + what + ":" + str(lat) + ':' + str(lng) + ":#ihave" api.updateStatus(tweet) return render_to_response('have/add.html')
def pegar_coordenadas_rotas(arquivo_rotas): """ Função que retorna uma lista contendo um dicionário com as informações das rotas passada no arquivo, este dicionário contém as seguinte informações: 'rotas' -> Contem 'distancia' -> Distância em metros entre a origem e o destino 'tempo' -> Tempo em segundos entre a origem e o destino 'origem' -> Origem 'destino' -> Destino 'velocidade' -> Velocidade em metros por segundos """ maps = GoogleMaps() rotas = [] try: with open(arquivo_rotas, 'r') as f: content = f.readlines() for i in content: try: source = re.search('from:(.*?)to:(.*)', i).group(1) dest = re.search('from:(.*?)to:(.*)', i).group(2) except: sys.stderr.write("Sintaxe do arquivo de rotas errada, verifique a documentação\n\n") sys.exit(0) try: info = maps.directions(source, dest) routes = info['Directions']['Routes'][0]['Steps'] Distancia = info['Directions']['Distance']['meters'] Tempo = info['Directions']['Duration']['seconds'] Origem = info['Placemark'][0]['address'] Destino = info['Placemark'][1]['address'] corigem = info['Placemark'][0]['Point']['coordinates'] cdestino = info['Placemark'][1]['Point']['coordinates'] Velocidade = Distancia/Tempo rotas.append({'rotas':routes, 'distancia':Distancia, 'tempo':Tempo, 'origem':Origem, 'destino':Destino, 'velocidade':Velocidade, 'corigem': corigem, 'cdestino': cdestino}) except: sys.stderr.write('Rota inexistente para: Origem: {} Destino: {}\n'.format(source, dest)) except IOError: sys.stderr.write('Não foi possível abrir o arquivo de rotas\n') return rotas
def get_lat_lng(address, silent=False): """ address(unicode)からlat, lngを検索して返す silent = Trueだとエラーを出さない """ addr_utf8 = smart_str(address) try: gmaps = GoogleMaps(GOOGLE_MAPS_API_KEY) lat, lng = gmaps.address_to_latlng(addr_utf8) except GoogleMapsError: if silent: return None, None raise return str(lat), str(lng)
def dist_from(destination, location): gmaps = GoogleMaps( 'ABQIAAAAAPMmDP4HCUrLtqjxnhTeXRQV_yMSNSvbo2tmQzi3qOzMvFrzcRTFTor1bOkU8NE2pW1HDlgjEDlcIQ' ) try: origin = location destination = '6224 Agricultural Road Vancouver, B.C. CA V6T 1Z1' dirs = gmaps.directions(origin, destination, mode='walking') time = dirs['Directions']['Duration']['html'] dist = dirs['Directions']['Distance']['meters'] route = dirs['Directions']['Routes'][0] return dist except GoogleMapsError: return 10000
def query_obs(location): """ Query information about a given location. 'CFHT Hawaii' 'Roque de los muchachos, Canary Islands' 'Siding Spring, Australia' """ print "Where the f**k is", location gmaps = GoogleMaps() result = gmaps.geocode(location) pprint.pprint(result['Placemark'][0])
def getCoord(address): """ Get coordinates for location using Google Maps Geolocation API. Raises: serializers.ValidationError: Google Maps API could not find pair of coordinates suitable for address passed as input. Returns: dictionary: Geocoding information. """ start_time = time.time() gmaps = GoogleMaps(os.getenv("GOOGLE_KEY")) geocode_result = gmaps.geocode(address) data = {'long': {}, 'short': {}, 'location': {}} if geocode_result: for geolist in geocode_result: for item in geolist['address_components']: for category in item['types']: data['long'].update([(category, item['long_name'])]) data['short'].update([(category, item['short_name'])]) data['location'] = geolist['geometry']['location'] else: e = serializers.ValidationError('GeoCoding Error: Could not parse coordinates') capture_message(e) raise e print('--- Tiempo de ejecucion getCoord: {} segundos ---'.format((time.time() - start_time))) return data
def main(): keyfile = "MAP_KEY" MAP_KEY = '' # Get API key from a file try: with open(keyfile, 'r+') as fh: MAP_KEY = fh.readline() except FileNotFoundError: print('API key file does not exist. Exit the program.') exit() # Create gmaps try: gmaps = GoogleMaps(MAP_KEY) except ValueError: print('Invalid API key provided. Exit the program.') exit() # Get src_addr and dst_addr. Currently hardcoded. Need to be changed. src_addr = 'temple university' dst_addr = 'temple university ambler campus Learning Center Parking Lot' # Get distance and duration of src_addr and dst_addr # return format examples: {'text': '25.3 km', 'value': 25318}, {'text': '25.3 km', 'value': 25318} distance, duration = getLatLng(src_addr, dst_addr, gmaps) print(distance) print(duration) """
def find_destination(self, x1, y1, x2, y2): gmaps = GoogleMaps("AIzaSyAChNKxjgh7MmGPQ6CJOGa_-tjM8giIZe4") destination = gmaps.latlng_to_address(x2, y2) adress = gmaps.latlng_to_address(x1, y1) directions = gmaps.directions(address, destination) print(directions['Directions']['Distance']['meters'])
def return_result(qid, q_type): global pending_photo, pending_task, active_queries temp_pending_photo = copy.deepcopy(pending_photo) for k,v in pending_photo[qid].iteritems(): if (os.path.exists('query/' + k)): names = k.split('=') pending_task[qid][names[0]].remove(names[1]) if (len(pending_task[qid][names[0]]) == 1): del pending_task[qid][names[0]] #if len(pending_task[qid]) > 0: #kill_users(pending_task[qid]) ret_val = '' if (len(pending_photo[qid]) == 0): ret_val += "<h2>No relevent results.</h2>" del pending_photo[qid] del pending_task[qid] del active_queries[qid] return ret_val #print "q_type = " + str(q_type) # q_type = 0U if (q_type[0] == '0'): ret_val += "Query Object: <br> </br><img src=\"data:image/jpg;base64,{0}\" width=205><br> </br>".format(open('QUERY_IMAGE/' + q_type[1:]).read().encode('base64').replace('\n', '')) ret_val += 'Result Objects: <br> </br> <table border=1 bordercolor=#999999 width=600><tr>' gmaps = GoogleMaps() while (len(pending_photo[qid]) > 0): (k, v) = max(pending_photo[qid].iteritems(), key=operator.itemgetter(1)) temp = k.split('=') ret_val += "<td width=205>" if (os.path.exists('query/' + k)): ret_val += "<img src=\"data:image/jpg;base64,{0}\" width=205>".format(open('query/' + k).read().encode('base64').replace('\n', '')) else: ret_val += "<b>Warning:</b> Photo failed to be uploaded on time." #temp = v.split(',') #dd = datetime.datetime.fromtimestamp(long(temp[len(temp) - 2])/1000) #tt = dd.isoformat(' ') #destination = "a, b, c, d, e, f, g" #destination = gmaps.latlng_to_address(float(temp[3]), float(temp[2])) #dest = destination.split(', ') #ret_val += "<p><b><pre>Location: </b>{0}</pre></p>".format(dest[0]) ret_val += "<p><b><pre>Credit: </b>{0}</pre></p>".format(str(pending_photo[qid][k])) #del dest[0] #dest[-2] += ', ' + dest[-1] #del dest[-1] #for dests in dest: # ret_val += "<p><pre> {0}</pre></p>".format(dests) ret_val += "<p><b><pre>Name: </b>{0}</pre></p>".format(k) del pending_photo[qid][k] ret_val += "</td>" del pending_photo[qid] del pending_task[qid] del active_queries[qid] print 'Finish response to ('+str(qid)+'). ' print ' Now query set (' + str(active_queries)+')' print ' Pending photo ('+str(pending_photo)+')' print ' Pending task ('+str(pending_task)+')' return ret_val
def hello_monkey(): def chooseSymbol(line): if 'head' in line: return "head" elif 'roundabout' in line: return 'roundabout' elif 'right' in line: return "right" elif 'left' in line: return "left" elif 'merge' in line: return "merge" else: return 'none' body_message = str(request.values.get('Body', None)) latitude = body_message.split('_')[0] longitude = body_message.split('_')[1] destination = body_message.split('_')[2] mapService = GoogleMaps() directions = mapService.directions('RG7 5ND', 'RG7 5NN') message = "" #for step in directions['Directions']['Routes'][0]['Steps']: # message = message + step['descriptionHtml'] mapsUrl = 'https://maps.googleapis.com/maps/api/directions/json?origin=' + str( latitude) + ',' + str(longitude) + '&destination=' + str( destination) + '&mode=walking' response = urllib.urlopen(mapsUrl) data = yaml.load(response.read()) leg = data.get('routes')[0].get('legs')[0] general_data = leg.get('distance').get('text') + '_' + leg.get( 'duration').get('text') stepMessage = "" stepsArray = leg.get('steps') for step in stepsArray: line = step.get('html_instructions') stepMessage = stepMessage + line + '_' + step.get('distance').get( 'text') + '_' + chooseSymbol(line) + '/n' #message = str(directions)[0:100] #message = "Latitude: " + str(latitude) + " Longitude: " + str(longitude) + " Destination: " + str(destination) message = str(stepMessage) resp = twilio.twiml.Response() resp.message(message) return str(resp)
def normalize_street_address(raw_address_string): gm = GoogleMaps() # Add API key for premium Google Maps service result = None try: data = gm.geocode(raw_address_string) if data is not None: result = NormalizedAddress(data) except KeyError: result = None except GoogleMapsError as ex: if ex.message != GoogleMapsError.G_GEO_UNKNOWN_ADDRESS: raise ex return result
def main(): gmaps = GoogleMaps() cr = csv.reader(open("mark.csv", "rb")) dic = dict() i = 0 for row in cr: if not row[0]: break if i == 0: i += 1 continue print row[2] #address=row[2] state = lookup(row[2]) text = row[14] a = text.split('/') if int(a[0]) > 6: date = 'winter' else: date = 'summer' if state not in dic: dic[state] = dict() if date not in dic[state]: dic[state][date] = dict() if row[5] not in dic[state][date]: dic[state][date][row[5]] = list() if row[6] not in dic[state][date][row[5]]: dic[state][date][row[5]].append(row[6]) for state in dic: print state, for date in dic[state]: print date for order in dic[state][date]: print dic[state][date][order] for state in dic: for date in dic[state]: if not state: state1 = 'statenotfoun' else: state1 = state if not date: date1 = 'datenotfound' else: date1 = date if not os.path.exists('./ir'): os.makedirs('./ir') f = open('./ir/' + state1 + date1 + '.txt', 'a') for order in dic[state][date]: i = 0 while i < len(dic[state][date][order]): f.write(dic[state][date][order][i]) f.write(' ') i += 1 f.write('\n')
def getPlaceID(self, address_line1, address_line2, area, city, state, country, pincode): gmaps = GoogleMaps('AIzaSyBoy1plslvW_UTSM3JTWNLijJL1KjsKf60') address = str(address_line1) + ',' + str(address_line2) + ',' + str( area) + ',' + str(city) + ',' + str(state) + ',' + str( country) + ',' + str(pincode) geocode_result = gmaps.geocode(address) print(geocode_result[0]['formatted_address']) place_id = geocode_result[0]['place_id'] return place_id
def getLocation(address_line1,address_line2,area,city,state,country,pincode): gmaps = GoogleMaps('AIzaSyBoy1plslvW_UTSM3JTWNLijJL1KjsKf60') address = str(address_line1)+ ',' + str(address_line2)+ ',' + str(area) + ',' + str(city) + ',' + str(state) + ',' + str(country) + ',' + str(pincode) geocode_result = gmaps.geocode(address) lat = geocode_result[0]['geometry']['location'] ['lat'] lon = geocode_result[0]['geometry']['location']['lng'] print(lat,lon) location = "SRID=4326;POINT ("+str(lat) + " " + str(lon)+")" print(location) return location
def retrieve(endpoint, api_key): gmaps = GoogleMaps(api_key) url = endpoint + '?' + urllib.urlencode([("query",query)]) + '&format=text%2Fcsv' header = None print >> sys.stderr, url for line in csv.reader(urllib.urlopen(url),delimiter=","): if header == None: header = line continue addressURI = line[0] address = ", ".join([x for x in line[1:] if x != ""]) try: lat, lng = gmaps.address_to_latlng(address) except GoogleMapsError: print >> sys.stderr, 'GoogleMapsError' print '{},{},{}'.format(addressURI,lat,lng)
def test_local_search(self): """Test googlemaps local_search().""" gmaps = GoogleMaps(GMAPS_API_KEY, referrer_url='http://www.google.com/') local = gmaps.local_search('sushi san francisco, ca') result = local['responseData']['results'][0] self.assertEqual(result['titleNoFormatting'], 'Sushi Groove') results = gmaps.local_search('Starbucks Los Angeles, CA', numresults=GoogleMaps.MAX_LOCAL_RESULTS) self.assertEqual(results['responseStatus'], googlemaps.STATUS_OK) self.assertNotEqual(results['responseData'], None) self.assertNotEqual(results['responseData']['cursor'], None) results = results['responseData']['results'] self.assertEqual(len(results), GoogleMaps.MAX_LOCAL_RESULTS) for result in results: self.assertEqual(result['GsearchResultClass'], 'GlocalSearch') self.assert_( result['titleNoFormatting'].lower().find('starbucks') >= 0) self.assertEqual(result['region'], 'CA')
def main(): output = '/net/casfsb/vol/ssrchome/active_users/ceholden/img_names.txt' f = codecs.open(output, 'w', encoding='utf-8') # refimg = '/net/casrs1/volumes/cas/landsat25/reference_images/catalog' # os.chdir(refimg) # GoogleMaps API key apik = 'AIzaSyA2w-3WNR5joUnHa4K7WDs2eyC-nzjr3fE' gmaps = GoogleMaps(apik)
def compress(address): try: gmaps = GoogleMaps('AIzaSyAH-SEZ1C_8Kb1ACyPCZZpZAJKKDuWD3Ro') geocode_result = gmaps.geocode(address) return geocode_result[0]['geometry']['location'][ 'lat'], geocode_result[0]['geometry']['location']['lng'] except IndexError: print("Address was wrong...") return "null", "null" except Exception as e: print("Unexpected error occurred.", e)
def add_coordinate_info(df, api_key): gmaps = GoogleMaps(api_key) df['long'] = "" df['lat'] = "" long = [] lat = [] for location in progress_bar(df.location): long_, lat_ = get_lat_long(location, gmaps) long.append(long_) lat.append(lat_) df.long = long df.lat = lat return df.reset_index(drop=True)
def getCoord(location): start_time = time.time() msj = '' gmaps = GoogleMaps(os.getenv("GOOGLE_KEY")) wk = [] for key in location.keys(): if 'name' not in key: wk.append(key) address = normalizeWord(re.sub(',', '', ', '.join(value for value in dict(zip(wk, [location[k] for k in wk])).values() if value), 1)) print(f"ADDRESS: {address}") geocode_result = gmaps.geocode(address) data = {'long': {}, 'short': {}, 'location': {}} if geocode_result: for geolist in geocode_result: for item in geolist['address_components']: for category in item['types']: data['long'].update([(category, item['long_name'])]) data['short'].update([(category, item['short_name'])]) data['location'] = geolist['geometry']['location'] else: msj = 'Coordinates not found. Please check Address sent' try: data['long']['administrative_area_level_1'] = getLocal('provincias', [dict(nombre=data.get('long').get('administrative_area_level_1'))]).get('nombre', None) except IndexError: raise serializers.ValidationError('Could not validate Locality') # print('location country: {} - gmaps country: {}'.format(location['country'], data.get('long').get('country'))) # print('gmaps route: {}'.format(data.get('short').get('route'))) print(f"DATA: {data['long']['administrative_area_level_1']}") if data.get('long').get('country') == location['country'] and normalizeWord(data.get('long').get('administrative_area_level_1')) == normalizeWord(location['province']): if data.get('short').get('route'): location['street'] = data.get('short').get('route') if data.get('short').get('locality'): location['city'] = data.get('short').get('locality') location['province'] = data.get('long').get('administrative_area_level_1') location['latitude'] = data.get('location').get('lat') location['longitude'] = data.get('location').get('lng') else: msj = 'Address not Validated' print(data['long']['administrative_area_level_1']) print('--- Tiempo de ejecucion getCoord: {} segundos ---'.format((time.time() - start_time))) return location, msj return location, msj
def test_reverse_geocode(self): """Test googlemaps reverse_geocode() and latlng_to_address()""" lat, lng = 40.714224, -73.961452 gmaps = GoogleMaps(GMAPS_API_KEY) result = gmaps.reverse_geocode(lat, lng) self.assertEqual(result['Status']['code'], 200) result = result['Placemark'][0] self.assertEqual(searchkey(result, 'CountryName'), 'USA') self.assertEqual(searchkey(result, 'PostalCodeNumber'), '11211') self.assertEqual(searchkey(result, 'ThoroughfareName'), '277 Bedford Ave') self.assertEqual(searchkey(result, 'LocalityName'), 'Brooklyn') self.assertEqual(searchkey(result, 'AdministrativeAreaName'), 'NY') self.assertEqual(searchkey(result, 'CountryNameCode'), 'US') addr = searchkey(result, 'address') self.assertEqual(addr, '277 Bedford Ave, Brooklyn, NY 11211, USA') lat2, lng2 = searchkey(result, 'coordinates')[1::-1] self.assertAlmostEquals(lat, lat2, 3) self.assertAlmostEquals(lng, lng2, 3) addr2 = gmaps.latlng_to_address(lat, lng) self.assertEqual(addr, addr2)
def get_coordinates(address: str, api_key: str) -> tuple: """ Takes in a string address and Google API key. Returns a tuple with latitude and longitude. """ gmaps = GoogleMaps(api_key) geocode_result = gmaps.geocode(address) try: lat = geocode_result[0]['geometry']['location']['lat'] long = geocode_result[0]['geometry']['location']['lng'] return lat, long except IndexError: print(f'Error: coordinates not found for location: {address}') return 0, 0
def get_coord_dir(direction): load_dotenv() G_KEY = os.getenv("KEY_GOOGLE") gmaps = GoogleMaps(G_KEY) geocode_result = gmaps.geocode(direction) try: lat = geocode_result[0]["geometry"]["location"]["lat"] lon = geocode_result[0]["geometry"]["location"]["lng"] return lat, lon except: lat = None lon = None print('At least I tried')
def getLocationByResourceId(r_id): class Map: def __init__(self, name, lat, lng): self.name = name self.lat = lat self.lng = lng api_key = "AIzaSyCeHf-jcEx21QPuV7BZOUOukikZ-bQYxDA" google = GoogleMaps(api_key) location = ResourcesHandler().getLocationByResourceId(r_id) geocode_result = google.geocode(location + ', Puerto Rico') lat = geocode_result[0]['geometry']['location']['lat'] lng = geocode_result[0]['geometry']['location']['lng'] map = Map(location, lat, lng) return render_template('map.html', map=map)
def storeloc(self, x): try: message = " " api_key = 'YOUR-API-KEY' gmaps = GoogleMaps(api_key) geocode_result = gmaps.geocode(x)[0] lat = geocode_result["geometry"]["location"]["lat"] lng = geocode_result["geometry"]["location"]["lng"] store = gmaps.places_nearby(location=(lat, lng), type='store', radius=500) for i in range(0, 5): message = message + str(store["results"][i]["name"] + "\n") return message except: message = "You have Entered a invalid input please try again!" return message