Example #1
0
def profile(request):
    u = User.objects.get(username=request.session['user'])
    wishlist = [Wish(u.username, i.item, i.store, i.count, i.metric) for i in Item.objects.filter(user=u)]
    stores = [store for store in open(os.path.join(settings.BASE_DIR, "cost/shopping/stores.txt"),"r")]
    users = User.objects.all().exclude(username=request.session['user'])
    addsend = [a.address for a in PickupLocation.objects.filter(user=u)]
    google_maps = GoogleMaps(api_key='AIzaSyC8hihi26xJqO77v4R2qJMii0cn6S2eW8w')
    userwishlist = []
    for user in users:
    	addrec = []
    	addr = PickupLocation.objects.filter(user=user)
    	for a in addr:
    		addrec.append(a.address)
    	
    	items = google_maps.distance(addrec, addsend).all()
    	for item in items:
    		if item.distance.miles <= 10:
    			userwishlist.append(Wish(i.user, i.item, i.store) for i in Item.objects.filter(user=user))
    			break
    	
    userwishlist = [Wish(i.user, i.item, i.store, i.count, i.metric) for i in Item.objects.all().exclude(user=u)]
    mywishlist = [Wish(i.receiver, i.item, i.store, i.count, i.metric) for i in UserItem.objects.filter(buyer=u)]
    try:
    	locs = PickupLocation.objects.filter(user=u)
    except:
    	locs = []
    c = {'STATIC_URL':settings.STATIC_URL, 'user':request.session['user'], 'wishlist':wishlist, 'mywishlist':mywishlist, 'userwishlist':userwishlist, 'stores':stores, 'locs':locs, 'feedbackform':FeedbackForm()}
    return render(request, "shopping_profile.html", c)
Example #2
0
def new_property(request):
    # If the user is submitting the form
    if request.method == "POST":

        # Get the instance of the form filled with the submitted data
        # form = PropertyForm(request.POST)
        form = PropertyForm(request.POST, request.FILES)
        # Django will check the form's validity for you
        if form.is_valid():

            # Saving the form will create a new Property object
            if form.save():
                data = form.cleaned_data
                property_address = data['address']
                google_maps = GoogleMaps(api_key='AIzaSyDlHBtlOb1-JpUPZ8CHAZqaNha6Uw_l_ow')
                location_info = google_maps.query(location=property_address)
                location_info = location_info.first()
                Property.objects.filter(address=property_address).update(xcoordinate=location_info.lat)
                Property.objects.filter(address=property_address).update(ycoordinate=location_info.lng)

                # After saving, redirect the user to add propertynotes
                return redirect("new_propertynotes")

    # Else if the user is looking at the form page
    else:
        form = PropertyForm()

    data = {'form': form}

    return render(request, "properties/add_property.html", data)
Example #3
0
def get_geolocation():
	# get Geolocation (lat,lng) from google
	from geolocation.google_maps import GoogleMaps
	google_maps = GoogleMaps(api_key='AIzaSyBEQ64NGaq3p_kXC7DuCj55FZdLhpPCMO8')
	location = google_maps.search(location=LOCATION)
	my_location = location.first()
	return my_location
Example #4
0
def coordinates(address):
    coord=[]
    google_maps=GoogleMaps(api_key=key)
    location=google_maps.search(location=address)
    my_location=location.first()
    coord.append(my_location.lat)
    coord.append(my_location.lng)
    return coord
Example #5
0
def coordinates(address):
    coord = []
    google_maps = GoogleMaps(api_key=key)
    location = google_maps.search(location=address)
    my_location = location.first()
    coord.append(my_location.lat)
    coord.append(my_location.lng)
    return coord
Example #6
0
def setLocation(request):
	if request.method == "GET":
		return render(request, "shopping_location.html")
	elif request.method == "POST":
		google_maps = GoogleMaps(api_key='AIzaSyC8hihi26xJqO77v4R2qJMii0cn6S2eW8w') 
		location = google_maps.search(location=request.POST['address'])
		my = location.first()
		u = User.objects.get(username=request.session['user'])
		PickupLocation(user=u, address="%s %s %s %s" % (my.street_number, my.route, my.city, my.postal_code)).save()
		return HttpResponseRedirect("/shopping/profile")
Example #7
0
def map(request):

    #all_locations = Location.objects.all()

    address = "225 Bush Street San Francisco California"

    google_maps = GoogleMaps(api_key='AIzaSyDlHBtlOb1-JpUPZ8CHAZqaNha6Uw_l_ow')

    location_info = google_maps.query(location=address)

    location_info = location_info.first()

    data = {"location_info":location_info}


    return render(request, "map.html", data)
def make_postalcode(postalcode_string):
    """
        Takes in zipcode as a string, gets lat and long info using the GoogleMaps
        API, and adds the zipcode to the PostalCodes table.

    """
    google_maps = GoogleMaps(api_key=os.environ["GOOGLE_API_KEY"])
    location = google_maps.search(location=postalcode_string).first()

    print "\n\n\n\n Google Maps API: location is %r \n\n" % location

    a = PostalCode(postalcode=int(postalcode_string), latitude=location.lat, longitude=location.lng)

    db.session.add(a)
    db.session.commit()

    temp = PostalCode.query.get(int(postalcode_string))
    print "****************\n\n\n\n\n MADE POSTALCODE %r\n\n\n\n\n*************" % temp
Example #9
0
def main():
	print ("hello world")
	currentTime = []
	address = '1280 Main street, Hamilton ON'
	google_maps = GoogleMaps(api_key='AIzaSyAb649ImqHvCeKtAA6YdT3Q6WbRRH2FrrQ')
	location = google_maps.search(location=address)  
	my_location = location.first()
	locationdata = (str(my_location.lat) + ',' + str(my_location.lng))
	timedata = datetime.datetime.now()
	current = str(timedata)
	currentTime. append(current[17:19])
	currentTime. append(current[14:16])
	currentTime. append(current[11:13])
	currentTime. append(current[8:10])
	currentTime. append(current[5:7])
	currentTime. append(current[2:4])
	print(locationdata)
	
	print currentTime[0] + ',' + currentTime[1] + ',' + currentTime[2] + ',' + currentTime[3] + ',' + currentTime[4] + ',' + currentTime[5]
Example #10
0
def main():
    print("hello world")
    currentTime = []
    address = '1280 Main street, Hamilton ON'
    google_maps = GoogleMaps(api_key='AIzaSyAb649ImqHvCeKtAA6YdT3Q6WbRRH2FrrQ')
    location = google_maps.search(location=address)
    my_location = location.first()
    locationdata = (str(my_location.lat) + ',' + str(my_location.lng))
    timedata = datetime.datetime.now()
    current = str(timedata)
    currentTime.append(current[17:19])
    currentTime.append(current[14:16])
    currentTime.append(current[11:13])
    currentTime.append(current[8:10])
    currentTime.append(current[5:7])
    currentTime.append(current[2:4])
    print(locationdata)

    print currentTime[0] + ',' + currentTime[1] + ',' + currentTime[
        2] + ',' + currentTime[3] + ',' + currentTime[4] + ',' + currentTime[5]
Example #11
0
def new_property(request):

    s3_url = "https://homedbbucket.s3.amazonaws.com/"
    # If the user is submitting the form
    if request.method == "POST":

        # Get the instance of the form filled with the submitted data
        form = PropertyForm(request.POST, request.FILES)
        # Django will check the form's validity
        if form.is_valid():

            # Saving the form will create a new Property object
            if form.save():
                data = form.cleaned_data
                #using property address to lat and lng info from google map, then update table
                property_address = data['address']
                google_maps = GoogleMaps(api_key=GOOGLE_API_KEY)
                location_info = google_maps.query(location=property_address)
                location_info = location_info.first()
                Property.objects.filter(address=property_address).update(xcoordinate=location_info.lat)
                Property.objects.filter(address=property_address).update(ycoordinate=location_info.lng)

                # After saving, redirect the user to add propertynotes
                return redirect("/properties/")
            else:
                print "not saved"
        else:
            print "form not valid"

    # Else if the user is looking at the form page
    else:
        form = PropertyForm()
        print "post failed"

    #S3 bucket
    data = {'form': form, 's3_url': s3_url}

    return render(request, "properties/add_property.html", data)
Example #12
0
 def setUp(self):
     self.google_maps = GoogleMaps(api_key=TEST_API_KEY)
Example #13
0
def search_radius(search_center, postalcodes, radius):
    """ Finds zipcodes in the database that are within a search radius of a
        location.

        This uses the python library geolocation-python, which uses the
        GoogleMaps API.

        Takes in search center as a string, postalcodes as a list of tuples
        (because that is the format returned from the database), and search
        radius in miles as an integer. The function returns the list of
        postal codes in the given list that are within the given radius.

    """
    # Future versions: make a table in the database to store distance search
    # results.
    # For now store frequest searches in a dictionary to prevent eof error,
    # likely from hitting Google Maps API too frequently within a given
    # amount of time.
    distances = {'94612': {'94109': 11.2468,
                           '94612': 0.0,
                           '94040': 45.4221,
                           '94115': 13.2973,
                           '95376': 53.1893,
                           '94043': 39.0842,
                           '10013': 2899.3124,
                           },
                 '94109': {'94109': 0.0,
                           '94612': 10.9361,
                           '94040': 38.9599,
                           '94115': 1.2427,
                           '95376': 62.137,
                           '10013': 2904.9047,
                           '94043': 37.2201,
                           },
                 }

    # SQLite returns the distinct postal codes as a list of tuples. Convert this
    # to a list of postal code strings.
    postalcodes_in_db = []

    for postalcode in postalcodes:
        postalcodes_in_db.append(postalcode[0])

    distinct_postalcodes = postalcodes_in_db
    postalcodes_within_radius = []

    if search_center in distances:
        distinct_postalcodes = []
        postalcodes_to_remove = []

        for postalcode in postalcodes_in_db:
            if postalcode in distances[search_center]:
                if distances[search_center][postalcode] <= radius:
                    postalcodes_within_radius.append(postalcode)
                # Always add postalcode to the list of postal codes to remove.
                postalcodes_to_remove.append(postalcode)

        # Check if there are still postal codes to check.
        if len(postalcodes_in_db) > len(postalcodes_to_remove):
            distinct_postalcodes = [postalcode for postalcode in postalcodes_in_db if postalcode not in postalcodes_to_remove]

    # Use GoogleMaps API there are still things left in distinct_postalcodes
    if distinct_postalcodes:
        google_maps = GoogleMaps(api_key=os.environ['GOOGLE_API_KEY'])

        # Put search center in a list because that is how the the geolocation
        # distance module takes it in as a parameter
        search_center = [search_center]

        # Now we can calculate distances.
        items = google_maps.distance(search_center, distinct_postalcodes).all()

        # Items is list of distance matrix object thingies. Each has an origin,
        # destination, and distance between the origin and destination.
        # First we'll take out the matrix thingies within the search
        # radius of the given search center.
        matrixthingies = []
        for item in items:
            if (item.distance.miles <= radius):
                matrixthingies.append(item)

        # Now we pull out the user location info from the matrixthingies. This info
        # has the city, state, zipcode and country.
        destinations = []
        for thingy in matrixthingies:
            destinations.append(thingy.destination)

        # Now we pull out the zipcode from the list of destinations.
        for destination in destinations:
            line = destination.split()
            postalcode = line[-2].replace(",", "")
            postalcodes_within_radius.append(postalcode)

    return postalcodes_within_radius
Example #14
0
 def setUp(self):
     self.google_maps = GoogleMaps(api_key=TEST_API_KEY)
Example #15
0
class GeolocationTest(unittest.TestCase):
    def setUp(self):
        self.google_maps = GoogleMaps(api_key=TEST_API_KEY)

    def test_query(self):
        address = "New York City Wall Street 15"

        location = self.google_maps.search(address)

        self.assertIsNotNone(location.all())

    def test_city(self):
        address = "New York City Wall Street 14"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('New York', my_location.city.decode('utf-8'))

    def test_route(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('Wall Street', my_location.route.decode('utf-8'))

    def test_country(self):
        address = "New York City Wall Street 110"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('United States', my_location.country.decode('utf-8'))

    def test_country_shortcut(self):
        address = "New York City Wall Street 2"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('US', my_location.country_shortcut.decode('utf-8'))

    def test_lat(self):
        address = "New York City Wall Street 1"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(40.7060081, my_location.lat)

    def test_lng(self):
        address = "New York City Wall Street 19"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(-74.0134436, my_location.lng)

    def test_formatted_address(self):
        address = "New York City Wall Street 124"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('Charging Bull, Broadway, New York, NY 10004, USA',
                         my_location.formatted_address)

    def test_administrative_area_level_1(self):
        address = "New York City Wall Street 125"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(
            'New York',
            my_location.administrative_area[0].name.decode('utf-8'))

    def test_administrative_area_level_2(self):
        address = "New York City Wall Street 126"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(
            'New York County',
            my_location.administrative_area[1].name.decode('utf-8'))

    def test_coding(self):
        address = "São Paulo"

        my_location = self.google_maps.search(address).first()

        self.assertEqual(u"São Paulo", my_location.city.decode('utf-8'))

    def test_latlng(self):
        lat = 37.4229210
        lng = -122.0852112

        my_location = self.google_maps.search(lat=lat, lng=lng).first()

        self.assertEqual('Mountain View', my_location.city.decode('utf-8'))
Example #16
0
import csv
from geolocation.google_maps import GoogleMaps

data_dir="/home/sachin/Data/EPFL/Sem 2/DH/newdata/"
google_maps = GoogleMaps(api_key=YOUR_KEY) 

with open(data_dir+"locations.csv","r") as fin:
 with open(data_dir+"coordinates.csv","w") as fout:
   reader = csv.reader(fin)
   writer=csv.writer(fout)
   for line in reader:
     location = google_maps.search(location=line[1]).first() # sends search to Google Maps.
     line.append(location.lat)
     line.append(location.lng)
     writer.writerow(line)
Example #17
0
from geolocation.google_maps import GoogleMaps
import IP2Location
import geoip2.database

# Enter GoogleMap API Key
google_maps = GoogleMaps(api_key='AIzaSyDJvXt5YtoHbMkQFBQk-Nok5SgdLwpF5R4')

#Define Address for Lookup
address = "New York City Wall Street 12"
location = google_maps.search(location=address)  # sends search to Google Maps.
my_location = location.first()  # returns only first location.

# Read GeoLite Database for IP Address Lookup
reader = geoip2.database.Reader('GeoLite2-City.mmdb')

#Enter IP Address for Lookup
response = reader.city('208.30.113.22')

#Print IP Address information
print("====================")
print(response.city.name)
print(response.postal.code)
print(response.location.latitude)
print(str(response.location.longitude) + " \n")

#Google Maps IP Coordinate look up
print("My Location - Lat " + str(my_location.lat))
print("My Location - Long " + str(my_location.lng))

# reverse geocode
lat = 40.7060008
Example #18
0
#Roman Hartmann
#[email protected]
#---------
#This script takes full street addresses from input csv, runs them through the google maps
#geocoding api, and writes results to output csv
#---------
#--external libraries used:
#pip install geolocation-python


from geolocation.google_maps import GoogleMaps
oGoogleMaps = GoogleMaps(api_key='AIzaSyDBkYIaHDM2ixsPpjyKAiSozYuIAx7rQTc') 

import csv
sCsvIn = "addresses_by_subnum.csv"
sCsvOut = "latlngs_by_subnum.csv"

i=0     #line counter

with open(sCsvOut, 'w') as fOut:
    oWriter = csv.writer(fOut)
    oWriter.writerow(["subnum", "address_lat_i", "address_lng_i"])
    
    with open(sCsvIn, 'r') as fIn:
        oReader = csv.reader(fIn)
        next(fIn)       #skip heading
        for lRow in oReader:
            i+= 1
            sSubnum = lRow[0]
            sAddress = lRow[1]
            print "{0}:\t{1} \t{2}".format(i, sSubnum, sAddress)
# -*- coding: utf-8 -*-
from geolocation.google_maps import GoogleMaps

if __name__ == "__main__":
    address = "New York City"

    google_maps = GoogleMaps(api_key='your_google_maps_key')

    lat = 40.7060008
    lng = -74.0088189

    location = google_maps.search(lat=lat, lng=lng)

    print location.all()

    my_location = location.first()

    print my_location.city
    print my_location.route
    print my_location.street_number
    print my_location.postal_code

    for administrative_area in my_location.administrative_area:
        print "%s: %s" % (administrative_area.area_type, administrative_area.name)

    print my_location.country
    print my_location.country_shortcut

    print my_location.formatted_address

    print my_location.lat
Example #20
0
# -*- coding: utf-8 -*-
from geolocation.google_maps import GoogleMaps

if __name__ == "__main__":
    address = "New York City"

    google_maps = GoogleMaps(api_key='your_google_maps_key')

    lat = 40.7060008
    lng = -74.0088189

    location = google_maps.search(lat=lat, lng=lng)

    print location.all()

    my_location = location.first()

    print my_location.city
    print my_location.route
    print my_location.street_number
    print my_location.postal_code

    for administrative_area in my_location.administrative_area:
        print "%s: %s" % (administrative_area.area_type,
                          administrative_area.name)

    print my_location.country
    print my_location.country_shortcut

    print my_location.formatted_address
Example #21
0
class DistanceMatrixTest(unittest.TestCase):
    def setUp(self):
        self.google_maps = GoogleMaps(api_key=TEST_API_KEY)

    def test_distance_matrix(self):
        origins = ['rybnik', 'oslo']
        destinations = ['zagrzeb']

        items = self.google_maps.distance(origins, destinations).all()

        for item in items:
            if item.origin == 'Rybnik, Poland':
                self.assertEqual(item.destination, 'Zagreb, Croatia')
                self.assertEqual(item.distance.kilometers, Decimal(713))
                self.assertEqual(item.distance.meters, 713000)
                self.assertEqual(item.distance.miles, 443.0368)
                self.assertEqual(str(item.duration), '0d 7h 7m 47s')

            if item.origin == 'Oslo, Norway':
                self.assertEqual(item.destination, 'Zagreb, Croatia')
                self.assertEqual(item.distance.kilometers, 2063)
                self.assertEqual(item.distance.meters, 2063000)
                self.assertEqual(item.distance.miles, 1281.8863)
                self.assertEqual(str(item.duration), '0d 21h 18m 29s')

    def test_distance_matrix_bicycling(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, const.MODE_BICYCLING).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1596)
        self.assertEqual(item.distance.meters, 1596000)
        self.assertEqual(item.distance.miles, 991.7065)
        self.assertEqual(str(item.duration), '3d 11h 7m 25s')

    def test_distance_matrix_walking(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, const.MODE_WALKING).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1380)
        self.assertEqual(item.distance.meters, 1380000)
        self.assertEqual(item.distance.miles, 857.4906)
        self.assertEqual(str(item.duration), '10d 9h 32m 16s')

    def test_distance_matrix_avoid_tolls(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, avoid=const.AVOID_TOLLS).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1542)
        self.assertEqual(item.distance.meters, 1542000)
        self.assertEqual(item.distance.miles, 958.1525)
        self.assertEqual(str(item.duration), '0d 16h 30m 40s')

    def test_distance_matrix_avoid_highways(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, avoid=const.AVOID_HIGHWAYS).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1491)
        self.assertEqual(item.distance.meters, 1491000)
        self.assertEqual(item.distance.miles, 926.4627)
        self.assertEqual(str(item.duration), '1d 1h 36m 6s')

    def test_distance_matrix_avoid_ferries(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, avoid=const.AVOID_FERRIES).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1851)
        self.assertEqual(item.distance.meters, 1851000)
        self.assertEqual(item.distance.miles, 1150.1559)
        self.assertEqual(str(item.duration), '0d 17h 35m 44s')
Example #22
0
#Roman Hartmann
#[email protected]
#---------
#This script takes full street addresses from input csv, runs them through the google maps
#geocoding api, and writes results to output csv
#---------
#--external libraries used:
#pip install geolocation-python

from geolocation.google_maps import GoogleMaps
oGoogleMaps = GoogleMaps(api_key='AIzaSyDBkYIaHDM2ixsPpjyKAiSozYuIAx7rQTc')

import csv
sCsvIn = "addresses_by_subnum.csv"
sCsvOut = "latlngs_by_subnum.csv"

i = 0  #line counter

with open(sCsvOut, 'w') as fOut:
    oWriter = csv.writer(fOut)
    oWriter.writerow(["subnum", "address_lat_i", "address_lng_i"])

    with open(sCsvIn, 'r') as fIn:
        oReader = csv.reader(fIn)
        next(fIn)  #skip heading
        for lRow in oReader:
            i += 1
            sSubnum = lRow[0]
            sAddress = lRow[1]
            print "{0}:\t{1} \t{2}".format(i, sSubnum, sAddress)
Example #23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import responses
import cgi
from postcodes import PostCoder
from geolocation.google_maps import GoogleMaps
g_m = GoogleMaps(api_key='AIzaSyAGwOOqFQPqt6xyG3UPVkh9dXGeNN4_kpg')
#gmaps = googlemaps.Client(key='AIzaSyAGwOOqFQPqt6xyG3UPVkh9dXGeNN4_kpg')
#from osmapi import OsmApi

pc = PostCoder()
#Userpc = raw_input("Enter Postcode")
print "Content-Type: text/html"
print
print """
<html>
  <head>
<style>
body {
  background-color: #d3d3d3;
  margin: 0 15%;
  font-family: Roboto;
  }
h1 {
  background-color: #4169E1;
  text-align: center;
  color: #ffffff;
  font-family: Roboto Condensed;
  font-weight: Bold;
  border-bottom: 20px solid #4169E1;
Example #24
0
class GeolocationTest(unittest.TestCase):
    def setUp(self):
        self.google_maps = GoogleMaps(api_key=TEST_API_KEY)

    def test_query(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        self.assertIsNotNone(location.all())

    def test_city(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('New York', my_location.city.decode('utf-8'))

    def test_route(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('Wall Street', my_location.route.decode('utf-8'))

    def test_country(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('United States', my_location.country.decode('utf-8'))

    def test_country_shortcut(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('US', my_location.country_shortcut.decode('utf-8'))

    def test_lat(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(40.7060008, my_location.lat)

    def test_lng(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(-74.0088189, my_location.lng)

    def test_formatted_address(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('Wall Street, New York, NY, USA',
                         my_location.formatted_address)

    def test_administrative_area_level_1(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(
            'New York',
            my_location.administrative_area[0].name.decode('utf-8'))

    def test_administrative_area_level_2(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(
            'New York County',
            my_location.administrative_area[1].name.decode('utf-8'))

    def test_coding(self):
        address = "São Paulo"

        my_location = self.google_maps.search(address).first()

        self.assertEqual(u"São Paulo", my_location.city.decode('utf-8'))

    def test_latlng(self):
        lat = 37.42291810
        lng = -122.08542120

        my_location = self.google_maps.search(lat=lat, lng=lng).first()

        self.assertEqual('Mountain View', my_location.city.decode('utf-8'))
# -- coding: utf-8 --

from geolocation.google_maps import GoogleMaps

address = 'New York City Wall Street 12'

google_maps = GoogleMaps(api_key='AIzaSyCqBaEO3JOEwpdTb31ImhXBU6t_7KBJWT8')

location_info = google_maps.query(location=address)

print location_info.all()  # return list of all location.

location_info = location_info.first()  # return only first location.

print location_info.city

print location_info.route

print location_info.street_number

print location_info.country

print location_info.lat

print location_info.lng
# -*- coding: utf-8 -*-
from geolocation.google_maps import GoogleMaps

if __name__ == "__main__":
    address = "New York City"

    google_maps = GoogleMaps(api_key='your_google_maps_key')

    location = google_maps.search(location=address)

    print location.all()

    my_location = location.first()

    print my_location.city
    print my_location.route
    print my_location.street_number
    print my_location.postal_code

    for administrative_area in my_location.administrative_area:
        print "%s: %s" % (administrative_area.area_type, administrative_area.name)

    print my_location.country
    print my_location.country_shortcut

    print my_location.formatted_address

    print my_location.lat
    print my_location.lng
Example #27
0
__author__ = 'liquidcable'
import time
import datetime
from geolocation.google_maps import GoogleMaps
from geolocation.distance_matrix import const

origins = ['30.519124,-97.793315']
destinations = ['30.2558053,-97.7391038']
google_maps = GoogleMaps(api_key='AIzaSyCnR7A11dEIwRHDhxOHpfmamptn3AGUNlo')

print ("-----------------------------------------------------------")
print ("Google Maps Distance - takes a new measurement every minute")
print ("Heath Holcomb | liquidcable.com | [email protected]")
print ("-----------------------------------------------------------")

items = google_maps.distance(origins, destinations).all()

for item in items:
    print ('origin: %s' % item.origin)
    print ('destination: %s' % item.destination)
    print ('km: %s' % item.distance.kilometers)
    print ('m: %s' % item.distance.meters)
    print ('miles: %s' % item.distance.miles)
    print ('duration: %s' % item.duration)
    print ('duration datetime: %s' % item.duration.datetime)

for x in range(0,90):
    print ("-----------------------------------------------------------")
    time.sleep(600)
    print ("time: " + time.strftime("%I:%M:%S"))
Example #28
0
# -*- coding: utf-8 -*-
from geolocation.google_maps import GoogleMaps
from geolocation.distance_matrix import const

if __name__ == "__main__":
    origins = ['rybnik', 'oslo']
    destinations = ['zagrzeb']

    google_maps = GoogleMaps(api_key='your_google_maps_key')

    items = google_maps.distance(origins, destinations).all()  # default mode parameter is const.MODE_DRIVING

    for item in items:
        print('origin: %s' % item.origin)
        print('destination: %s' % item.destination)
        print('km: %s' % item.distance.kilometers)
        print('m: %s' % item.distance.meters)
        print('miles: %s' % item.distance.miles)
        print('duration: %s' % item.duration)  # it returns str
        print('duration datetime: %s' % item.duration.datetime)  # it returns datetime

        # you can also get items from duration
        print('duration days: %s' % item.duration.days)
        print('duration hours: %s' % item.duration.hours)
        print('duration minutes: %s' % item.duration.minutes)
        print('duration seconds: %s' % item.duration.seconds)

    items = google_maps.distance(origins, destinations, const.MODE_BICYCLING).all()

    for item in items:
        print('origin: %s' % item.origin)
Example #29
0
import os
import string
import urllib2
#import lxml
import time
#import requests
import re
#import mechanize
from bs4 import BeautifulSoup
import csv
#import lxml.html
#from urlparse import urlparse
from geolocation.google_maps import GoogleMaps

google_maps = GoogleMaps(api_key='AIzaSyDevSd4Tb2ZZtl9bZqUhqViAdhQXVHV23k')

dir = os.path.dirname(os.path.abspath(__file__))

destination = dir+'/table.csv'
if os.path.isfile(destination) == True:    #prevents appending old version
    os.remove(destination)
table = open(destination,'w')

ids = ['MainContent_lblLocation','MainContent_lblAcctNum', 'MainContent_lblGenAssessment', 'MainContent_lblGenAppraisal', 'MainContent_lblPidLabel', 'MainContent_lblBldCount', 'MainContent_lblLndAcres','MainContent_lblLndAsmt', 'MainContent_lblLndAppr','MainContent_lblMblu']

categories = ['State', 'Town', 'Address', 'Account Number', 'General Assessment', 'General Appraisal', 'PID', 'Building Count', 'Land Acres', 'Land Assesment', 'Land Appraisal', 'MBLU', 'Lat', 'Long', 'URL']

dir = os.path.dirname(os.path.abspath(__file__))
baseURL = "http://gis.vgsi.com/providenceri/"
Example #30
0
from geolocation.google_maps import GoogleMaps
from geolocation.distance_matrix import const

address = "98 w 4th st dunkirk ny 14048"
#origins = ["501 Woodrow Avenue Dunkirk New York 14048"]
#destinations = ['36 Center street Fredonia New York 14063']
google_maps = GoogleMaps(api_key='AIzaSyBDrUT23Cl31dLl-T6ZRPERYefp8-nH7bY') 
#items = google_maps.distance(origins, destinations).all()  # default mode parameter is const.MODE_DRIVING.
location = google_maps.search(location=address) # sends search to Google Maps.

print(location.all()) # returns all locations.

my_location = location.first() # returns only first location.

print(my_location.city)
print(my_location.route)
print(my_location.street_number)
print(my_location.postal_code)

for administrative_area in my_location.administrative_area:
    print("{}: {}".format(administrative_area.area_type, administrative_area.name))

print(my_location.country)
print(my_location.country_shortcut)

print(my_location.formatted_address)

print(my_location.lat)
print(my_location.lng)

# reverse geocode
Example #31
0
class GeolocationTest(unittest.TestCase):
    def setUp(self):
        self.google_maps = GoogleMaps(api_key=TEST_API_KEY)

    def test_query(self):
        address = "New York City Wall Street 15"

        location = self.google_maps.search(address)

        self.assertIsNotNone(location.all())

    def test_city(self):
        address = "New York City Wall Street 14"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('New York', my_location.city.decode('utf-8'))

    def test_route(self):
        address = "New York City Wall Street 12"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('Wall Street', my_location.route.decode('utf-8'))

    def test_country(self):
        address = "New York City Wall Street 110"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('United States', my_location.country.decode('utf-8'))

    def test_country_shortcut(self):
        address = "New York City Wall Street 2"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('US', my_location.country_shortcut.decode('utf-8'))

    def test_lat(self):
        address = "New York City Wall Street 1"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertAlmostEqual(40.7060081, my_location.lat, 2)

    def test_lng(self):
        address = "New York City Wall Street 19"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertAlmostEqual(-74.0134436, my_location.lng, 2)

    def test_formatted_address(self):
        address = "New York City Wall Street 124"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual('Charging Bull, Broadway, New York, NY 10004, USA',
                         my_location.formatted_address)

    def test_administrative_area_level_1(self):
        address = "New York City Wall Street 125"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(
            'New York',
            my_location.administrative_area[0].name.decode('utf-8'))

    def test_administrative_area_level_2(self):
        address = "New York City Wall Street 126"

        location = self.google_maps.search(address)

        my_location = location.first()

        self.assertEqual(
            'New York County',
            my_location.administrative_area[1].name.decode('utf-8'))

    def test_coding(self):
        address = "São Paulo"

        my_location = self.google_maps.search(address).first()

        self.assertEqual(u"São Paulo", my_location.city.decode('utf-8'))

    def test_latlng(self):
        lat = 37.4229210
        lng = -122.0852112

        my_location = self.google_maps.search(lat=lat, lng=lng).first()

        self.assertEqual('Mountain View', my_location.city.decode('utf-8'))

    def test_administrative_area_resets(self):
        address = "São Paulo"
        sao_paulo = self.google_maps.search(address).first()

        address = "Houston, TX"
        houston = self.google_maps.search(address).first()

        self.assertNotEqual(sao_paulo, houston)
Example #32
0
# -*- coding: utf-8 -*-
from geolocation.google_maps import GoogleMaps
from geolocation.distance_matrix import const

if __name__ == "__main__":
    origins = ['rybnik', 'oslo']
    destinations = ['zagrzeb']

    google_maps = GoogleMaps(api_key='your_google_maps_key')

    items = google_maps.distance(origins, destinations).all()  # default mode parameter is const.MODE_DRIVING

    for item in items:
        print('origin: %s' % item.origin)
        print('destination: %s' % item.destination)
        print('km: %s' % item.distance.kilometers)
        print('m: %s' % item.distance.meters)
        print('miles: %s' % item.distance.miles)
        print('duration: %s' % item.duration)  # it returns str
        print('duration datetime: %s' % item.duration.datetime)  # it returns datetime

        # you can also get items from duration
        print('duration days: %s' % item.duration.days)
        print('duration hours: %s' % item.duration.hours)
        print('duration minutes: %s' % item.duration.minutes)
        print('duration seconds: %s' % item.duration.seconds)

    items = google_maps.distance(origins, destinations, const.MODE_BICYCLING).all()

    for item in items:
        print('origin: %s' % item.origin)
Example #33
0
class DistanceMatrixTest(unittest.TestCase):
    def setUp(self):
        self.google_maps = GoogleMaps(api_key=TEST_API_KEY)
        self.duration_regex = r'([0-9]*)d ([0-9]*)h ([0-9]*)m ([0-9]*)s'
        self.delta_km = 25
        self.delta_m = 25000
        self.delta_miles = 25

    def test_distance_matrix(self):
        origins = ['rybnik', 'oslo']
        destinations = ['zagrzeb']

        items = self.google_maps.distance(origins, destinations).all()

        for item in items:
            if item.origin == 'Rybnik, Poland':
                self.assertEqual(item.destination, 'Zagreb, Croatia')
                self.assertAlmostEqual(float(709), item.distance.kilometers, delta=self.delta_km)
                self.assertAlmostEqual(float(713000), item.distance.meters, delta=self.delta_m)
                self.assertAlmostEqual(float(443.0368), item.distance.miles, delta=self.delta_miles)
                self.assertRegexpMatches(str(item.duration), self.duration_regex)

            if item.origin == 'Oslo, Norway':
                self.assertEqual(item.destination, 'Zagreb, Croatia')
                self.assertAlmostEqual(float(2063), item.distance.kilometers, delta=self.delta_km)
                self.assertAlmostEqual(float(2063000), item.distance.meters, delta=self.delta_m)
                self.assertAlmostEqual(float(1281.8863), item.distance.miles, delta=self.delta_miles)
                self.assertRegexpMatches(str(item.duration), self.duration_regex)

    def test_distance_matrix_bicycling(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, const.MODE_BICYCLING).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertAlmostEqual(float(1596), item.distance.kilometers, delta=self.delta_km)
        self.assertAlmostEqual(float(1596000), item.distance.meters, delta=self.delta_m)
        self.assertAlmostEqual(float(991.7065), item.distance.miles, delta=self.delta_miles)
        self.assertRegexpMatches(str(item.duration), self.duration_regex)

    def test_distance_matrix_walking(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, const.MODE_WALKING).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertAlmostEqual(float(1380), item.distance.kilometers, delta=self.delta_km)
        self.assertAlmostEqual(float(1380000), item.distance.meters, delta=self.delta_m)
        self.assertAlmostEqual(float(857.4906), item.distance.miles, delta=self.delta_miles)
        self.assertRegexpMatches(str(item.duration), self.duration_regex)

    def test_distance_matrix_avoid_tolls(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, avoid=const.AVOID_TOLLS).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertAlmostEqual(float(1542), item.distance.kilometers, delta=self.delta_km)
        self.assertAlmostEqual(float(1542000), item.distance.meters, delta=self.delta_m)
        self.assertAlmostEqual(float(958.1525), item.distance.miles, delta=self.delta_miles)
        self.assertRegexpMatches(str(item.duration), self.duration_regex)

    def test_distance_matrix_avoid_highways(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, avoid=const.AVOID_HIGHWAYS).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertAlmostEqual(float(1542), item.distance.kilometers, delta=self.delta_km)
        self.assertAlmostEqual(float(1542000), item.distance.meters, delta=self.delta_m)
        self.assertAlmostEqual(float(958.1525), item.distance.miles, delta=self.delta_miles)
        self.assertRegexpMatches(str(item.duration), self.duration_regex)

    def test_distance_matrix_avoid_ferries(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations, avoid=const.AVOID_FERRIES).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertAlmostEqual(float(1851), item.distance.kilometers, delta=self.delta_km)
        self.assertAlmostEqual(float(1851000), item.distance.meters, delta=self.delta_m)
        self.assertAlmostEqual(float(1150.1559), item.distance.miles, delta=self.delta_miles)
        self.assertRegexpMatches(str(item.duration), self.duration_regex)
Example #34
0
class DistanceMatrixTest(unittest.TestCase):
    def setUp(self):
        self.google_maps = GoogleMaps(api_key=TEST_API_KEY)

    def test_distance_matrix(self):
        origins = ['rybnik', 'oslo']
        destinations = ['zagrzeb']

        items = self.google_maps.distance(origins, destinations).all()

        for item in items:
            if item.origin == 'Rybnik, Poland':
                self.assertEqual(item.destination, 'Zagreb, Croatia')
                self.assertEqual(item.distance.kilometers, Decimal(713))
                self.assertEqual(item.distance.meters, 713000)
                self.assertEqual(item.distance.miles, 443.0368)
                self.assertEqual(str(item.duration), '0d 7h 7m 47s')

            if item.origin == 'Oslo, Norway':
                self.assertEqual(item.destination, 'Zagreb, Croatia')
                self.assertEqual(item.distance.kilometers, 2063)
                self.assertEqual(item.distance.meters, 2063000)
                self.assertEqual(item.distance.miles, 1281.8863)
                self.assertEqual(str(item.duration), '0d 21h 18m 29s')

    def test_distance_matrix_bicycling(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations,
                                         const.MODE_BICYCLING).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1596)
        self.assertEqual(item.distance.meters, 1596000)
        self.assertEqual(item.distance.miles, 991.7065)
        self.assertEqual(str(item.duration), '3d 11h 7m 25s')

    def test_distance_matrix_walking(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins, destinations,
                                         const.MODE_WALKING).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1380)
        self.assertEqual(item.distance.meters, 1380000)
        self.assertEqual(item.distance.miles, 857.4906)
        self.assertEqual(str(item.duration), '10d 9h 32m 16s')

    def test_distance_matrix_avoid_tolls(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins,
                                         destinations,
                                         avoid=const.AVOID_TOLLS).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1542)
        self.assertEqual(item.distance.meters, 1542000)
        self.assertEqual(item.distance.miles, 958.1525)
        self.assertEqual(str(item.duration), '0d 16h 30m 40s')

    def test_distance_matrix_avoid_highways(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins,
                                         destinations,
                                         avoid=const.AVOID_HIGHWAYS).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1491)
        self.assertEqual(item.distance.meters, 1491000)
        self.assertEqual(item.distance.miles, 926.4627)
        self.assertEqual(str(item.duration), '1d 1h 36m 6s')

    def test_distance_matrix_avoid_ferries(self):
        origins = ['rybnik']
        destinations = ['oslo']

        item = self.google_maps.distance(origins,
                                         destinations,
                                         avoid=const.AVOID_FERRIES).first()

        self.assertEqual(item.origin, 'Rybnik, Poland')
        self.assertEqual(item.destination, 'Oslo, Norway')
        self.assertEqual(item.distance.kilometers, 1851)
        self.assertEqual(item.distance.meters, 1851000)
        self.assertEqual(item.distance.miles, 1150.1559)
        self.assertEqual(str(item.duration), '0d 17h 35m 44s')
Example #35
0
 def setUp(self):
     self.google_maps = GoogleMaps(api_key=TEST_API_KEY)
     self.duration_regex = r'([0-9]*)d ([0-9]*)h ([0-9]*)m ([0-9]*)s'
     self.delta_km = 25
     self.delta_m = 25000
     self.delta_miles = 25
Example #36
0
metro_tran = '/Users/xshuai/Documents/Projects/accessibilityscore/Metro Transit Zip Code.csv'

address = "818 West 46th St, Minneapolis MN"   # sample user input
#address = "55123"
#address = "610 Opperman Dr, Eagan, MN"
#address = '1455 Upper 55th St E, Inver Grove Heights, MN 55077'
apiKey='ffd1c56f9abcf84872116b4cc2dfcf31'  # api key for walk/transit score

walkscore = WalkScore(apiKey)
#transitscore = TransitScore(apiKey)

### extract location information  ####
geolocator = Nominatim()
location = geolocator.geocode(address)
#print(location.raw)
google_maps = GoogleMaps(api_key='AIzaSyAP3JK8NPEfz8OTdYCGNgpv6wYCUsx4gf8')
google_location = google_maps.search(location=address)
#print(google_location.all()) # returns all locations.

my_location = google_location.first() # returns only first location.


code_city = {}
code_score = {}
with open(metro_tran, 'rU') as infile:
    for index, line in enumerate(infile):
        if index == 0:
            continue
        content = line.rstrip('\n').split(',')
        #print(content)
        primary_city = content[0]
Example #37
0
from geolocation.google_maps import GoogleMaps

google_maps = GoogleMaps(api_key='AIzaSyBXW--FnarS7Ype4a0WZPTV-JVpHpIwPHA')

f = open('E:/city.txt', 'a+')

for line in open('e:\\project\\Data\\000\\Trajectory\\a.plt'):

    lat = line.split()[0]
    lng = line.split()[1]

    my_location = google_maps.search(lat=lat, lng=lng).first()

    print(my_location.city)
    print(my_location.route)
    print(my_location.street_number)
    print(my_location.postal_code)

    f.write(my_location.city + '  ')
    f.write(str(my_location.route) + '  ')
    f.write(my_location.postal_code + '\n')
    f.write(my_location.street_number + ' \n')

f.close()

#lat = 39.984333
#lng = 116.318417

#print lat
#print lng