Beispiel #1
0
    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
Beispiel #2
0
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))
Beispiel #3
0
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))
Beispiel #4
0
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']
Beispiel #5
0
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)
Beispiel #6
0
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 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 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'], 'OK')
        result = result['results'][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, 'formatted_address')
        self.assertEqual(addr, '285 Bedford Avenue, Brooklyn, NY 11211, USA')
        loc = searchkey(result, 'location')
        lat2, lng2 = loc['lat'], loc['lng']
        self.assertAlmostEquals(lat, lat2, 3)
        self.assertAlmostEquals(lng, lng2, 3)
        
        addr2 = gmaps.latlng_to_address(lat, lng)
        self.assertEqual(addr, addr2)
Beispiel #9
0
    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
Beispiel #10
0
    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)
Beispiel #11
0
# pip install googlemaps
from googlemaps import GoogleMaps 
api_key = 'AIzaSyA5nMPOn0fpv824YiL2sab5-NZejD9lXvA'
gmaps = GoogleMaps(api_key)
whitehouse = '1600 Pennsylvania Avenue, Washington, DC'
lat, lng = gmaps.address_to_latlng(whitehouse)
print lat, lng

destination = gmaps.latlng_to_address(38.897096, -77.036545)
print destination 

dlat, dlng = gmaps.address_to_latlng('326 Perkins Library, Durham, NC 27708')
print dlat, dlng 
duke = gmaps.latlng_to_address(dlat, dlng)
print duke 

local = gmaps.local_search('restaurant near ' + duke)
print local['responseData']['results'][0]['titleNoFormatting']

directions = gmaps.directions(duke, whitehouse)
print directions['Directions']['Distance']['meters']

for step in directions['Directions']['Routes'][0]['Steps']:
	print step['descriptionHtml']

embassies = [[38.917228,-77.0522365], 
	[38.9076502, -77.0370427], 
	[38.916944, -77.048739] ]

# TODO: write code to answer the following questions: 
# which embassy is closest to the White House in meters? how far? 
Beispiel #12
0
def computeTripLegsEmissions(request):
    startTime = datetime.datetime.now()
    post = request.POST
    transportMeanType = post['transportMeanType']
    gmaps = GoogleMaps(GOOGLE_MAPS_API_KEY)
    startLatLong = simplejson.loads(post['startLatLong'])
    endLatLong = simplejson.loads(post['endLatLong'])
    
    directions = gmaps.directions(gmaps.latlng_to_address(startLatLong[0], startLatLong[1]), \
                                  gmaps.latlng_to_address(endLatLong[0], endLatLong[1]) )
    drivingDistance = Decimal(directions['Directions']['Distance']['meters']) / 1000
    tripLeg= models.TripLeg.objects.get(id=post['tripLegId'])
    
    #get the transport mean used during this trip leg
    transportMean = tripLeg.transportMean

    if post['calculationMethod'] == 'tier1':
        #get tier1 calculation method id
        calculationMethod = models.C02CalculationMethod.objects.get(tier='1')
        
        if transportMeanType == 'generalCar':
            #get emission factor corresponding to this general car
            emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.GeneralCar),\
                                                                            transportMean_id=transportMean.id).emissionFactor            
        elif transportMeanType == 'bus':
            emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.Bus),\
                                                                            transportMean_id=transportMean.id).emissionFactor 
        elif transportMeanType == 'taxi':
            emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.Taxi),\
                                                                            transportMean_id=transportMean.id).emissionFactor 
        elif transportMeanType == 'motorcycle':
            emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.Motorcycle),\
                                                                            transportMean_id=transportMean.id).emissionFactor 
        elif transportMeanType == 'ferry':
            emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.Ferry),\
                                                                            transportMean_id=transportMean.id).emissionFactor 
        elif transportMeanType == 'rail':
            emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.Rail),\
                                                                            transportMean_id=transportMean.id).emissionFactor 
        elif transportMeanType == 'airplane':
            emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.Airplane),\
                                                                            transportMean_id=transportMean.id).emissionFactor                                                              
        ghgEmissions = drivingDistance * emissionFactor.directGHGEmissions
            
        #save the computed value
        tripLegEmission = models.TripLegCarbonEmission.objects.create(tripLeg=tripLeg, method=calculationMethod,\
                                                                          emissionFactor=emissionFactor, emissions=ghgEmissions)
    elif post['calculationMethod'] == 'tier2':
        #get tier2 calculation method id
        calculationMethod = models.C02CalculationMethod.objects.get(tier='2')
        #get emission factor corresponding to the specific car model
        emissionFactor = models.TransportMeanEmissionFactor.objects.get(transportMean_content_type=ContentType.objects.get_for_model(models.Car),\
                                                                            transportMean_id=transportMean.id).emissionFactor            
        ghgEmissions = drivingDistance * emissionFactor.directGHGEmissions
            
        #save the computed value
        tripLegEmission = models.TripLegCarbonEmission.objects.create(tripLeg=tripLeg, method=calculationMethod,\
                                                                          emissionFactor=emissionFactor, emissions=ghgEmissions)
    endTime = datetime.datetime.now()
    #createProvenanceGraph
    provManager = ProvManager()
    bundle = provManager.createTripLegEmissionGraph(tripLegEmission.id, calculationMethod.id, transportMean.id, transportMeanType,\
                                                            emissionFactor.id, emissionFactor.source.id, drivingDistance, tripLeg.id, tripLeg.startAddress.id,\
                                                            tripLeg.endAddress.id, startTime, endTime)
    tripLegEmission.provBundle = bundle
    tripLegEmission.save()

    
    json = simplejson.dumps( {'status': 'OK'} )
    
    return HttpResponse(json, mimetype='application/json')
 def test_latlng_to_address(self):
     gmaps = GoogleMaps(GMAPS_API_KEY)
     lat, lng = 40.714224, -73.961452
     address = '285 Bedford Ave, Brooklyn, NY 11211, USA'
     self.assertEqual(gmaps.latlng_to_address(lat, lng), address)
print 'google jkeuy' , ' ', gkey
gmap = GoogleMaps(gkey)
saxparser.parse('/usa/arao/trec/contexttrec12/contexts.txt',chandler)

for context in contextlist:
    js =    json.load( open('/usa/arao/trec/contexttrec12/yelpplaces/'+context.attribute['number']))
    businesslist = list()
    print 'num business in this contect' , ' ', len(js['businesses'])
    for business in js['businesses']:
        if business.get('gmaptime') is not None:
            businesslist.append(business)
            continue
     
        destlat = float(str(business['location']['coordinate']['latitude']))
        destlong = float(str(business['location']['coordinate']['longitude']))
        dest = gmap.latlng_to_address(destlat, destlong)
        originlat = float(context.attribute['lat'])
        originlong = float(context.attribute['long'])
        orig = gmap.latlng_to_address(originlat, originlong)
        directions  = None
        try:
            directions = gmap.directions(orig, dest)
        except:
            print 'problem with ', ' ', orig, '  ', dest 
            continue 
        if directions is None:
            continue
        meters = directions['Directions']['Distance']['meters']
        timesec =  directions['Directions']['Duration']['seconds']
        business['gmapdistance'] = meters
        business['gmaptime'] = timesec
                   
                        
            elif keyword == "REV":

                c.execute("SELECT * FROM Users WHERE number = '%s'" %texter)
                response = c.fetchone()
                print response
                if response != None:
                    print texter+" is registered"
                        
                    try:
                        lat = float(text.split()[1])
                        lng = float(text.split()[2])
                        
                        print lat, lng
                        destination = gmaps.latlng_to_address(lat,lng)
                        print destination
                        SEND(destination, texter)
                    except:
                        SEND("Invalid latitude or longitude", texter)

                else:
                    print texter+" is NOT registered"
                    SEND("You are not registered",texter)
                
            else:
                if text == "INFO":
                    SEND("GET INFO", texter)

                elif text == "REG":
                    c.execute("INSERT INTO Users VALUES ("+texter+")")
Beispiel #16
0
				check = steps['descriptionHtml']
				check = remove_html_tags(check)
				print check
	except:
	    print "Wystapil nieznany blad! Przepraszamy."
elif wybor == 2:
	try:
		cel1 = raw_input('Czego poszukujesz?: ')
		address3 = raw_input('W jakiej okolicy?: ')
		if address3 == "" or cel1 == "":
			print ""
			print "Prosze podac poprawne nazwy miejscowosci i punkty docelowe."
		else:
			lat3, lng3 = gmaps.address_to_latlng(cel1 + ' ' + address3)
			lat6, lng6 = gmaps.address_to_latlng(address3)
			miejsce = gmaps.latlng_to_address(lat6, lng6)
			destination3 = gmaps.latlng_to_address(lat3, lng3)
			local = gmaps.local_search(cel1 + ' ' + address3)
			print local['responseData']['results'][0]['titleNoFormatting']
			if miejsce != destination3:
				print destination3
			else:
				pass
	except:
		print "Wystapil nieznany blad! Przepraszamy."
elif wybor == 3:
	try:
		address4 = raw_input('Podaj nazwe miejscowosci startowej: ')
		cel2 = raw_input('Czego poszukujesz?: ')
		address5 = raw_input('Podaj miejscowosc, w ktorej szukac: ')
		if address4 == "" or address5 == "" or cel2 == "":
Beispiel #17
0
import googlemaps
from googlemaps import GoogleMaps
gmaps = GoogleMaps('ABQIAAAAU6aB_SumFVXY8JuehQcWXRRPdrwtlRIZKQUOo_MxBO_KFxU4HhRWfVQKeLerXiLRHZpWt_AaKWWZIg') #calls google maps with the API Key required
x=gmaps.address_to_latlng('dsa new delhi')
y=gmaps.latlng_to_address(x[0],x[1])
print x
print y
        lat = buf1[4]
        lng = buf1[5]
        u = buf1[3]
        splitsender = u.split(",")

        sender = splitsender[1]
        print "Latitude = " + lat
        print "Longitude = " + lng
        print "Sender = " + sender
        LAT = float(lat)
        LNG = float(lng)

        SerialPort.write("AT+CMGD=0\r\n")

        print "Loading address from Google Maps \n Please wait..."
        destination = gmaps.latlng_to_address(LAT, LNG)

        print "Ikaw ay papunta sa\n" + destination

        SerialPort.write("AT+CMGS=" + sender + "\r\n")
        time.sleep(1)
        print SerialPort.read(SerialPort.inWaiting())
        time.sleep(1)
        SerialPort.write(destination + "\x1A")
        print SerialPort.read(SerialPort.inWaiting())
        time.sleep(1)
        print "Confirmation Message Sent"

        print "Loading google earth....."
        import win32com.client
saxparser.parse('/usa/arao/trec/contexttrec12/contexts.txt', chandler)

for context in contextlist:
    js = json.load(
        open('/usa/arao/trec/contexttrec12/yelpplaces/' +
             context.attribute['number']))
    businesslist = list()
    print 'num business in this contect', ' ', len(js['businesses'])
    for business in js['businesses']:
        if business.get('gmaptime') is not None:
            businesslist.append(business)
            continue

        destlat = float(str(business['location']['coordinate']['latitude']))
        destlong = float(str(business['location']['coordinate']['longitude']))
        dest = gmap.latlng_to_address(destlat, destlong)
        originlat = float(context.attribute['lat'])
        originlong = float(context.attribute['long'])
        orig = gmap.latlng_to_address(originlat, originlong)
        directions = None
        try:
            directions = gmap.directions(orig, dest)
        except:
            print 'problem with ', ' ', orig, '  ', dest
            continue
        if directions is None:
            continue
        meters = directions['Directions']['Distance']['meters']
        timesec = directions['Directions']['Duration']['seconds']
        business['gmapdistance'] = meters
        business['gmaptime'] = timesec
Beispiel #20
0
route_list=[] # Holds the fetched data about the route
list_values=[] #holds the values to be input in sequence from number , source , destination
lat_a=0.0#lat of address
lat_d=0.0#lat of destination
lng_a=0.0
lng_d=0.0
lat_a,lng_a,lat_d,lng_d = checker()
#variable definition ends

list_values = read_file()
address = list_values[1]
destination = list_values[2]

#lat_a,lng_a = gmaps.address_to_latlng(address)
#print lat_a,lng_a
address = gmaps.latlng_to_address(lat_a,lng_a)
print address
#destination = destination + ',New Delhi ,India'
#lat_d,lng_d = gmaps.address_to_latlng(destination)
#print lat_d,lng_d
destination = gmaps.latlng_to_address(lat_d,lng_d)
print destination
directions = gmaps.directions(address, destination)
print directions

for step in directions['Directions']['Routes'][0]['Steps']:
    a=step['descriptionHtml']
    route_list.append(a)
#for i in listtemp:
#    print i
print '\n\n****Route Calculated****\n\n'