Example #1
0
    def displayAll(self):
        ''' Simple function that displays all parking garages on file 
            Parameters: N/A
            Returns: None 
        '''
        #Get the list of garages, filter for only garage objects, and make sure it is not empty
        garageList = os.listdir("garages")
        for item in garageList:
            parts = item.split(".")
            if parts[-1] != "pkl":
                garageList.remove(item)
        if not garageList:
            pop = Popup(title="Error",
                        content=Label(text="No Garages on File"),
                        size_hint=(None, None),
                        size=(200, 200))
            pop.open()
            return

        #For each garage on file, mark its location
        coder = GoogleGeocoder("AIzaSyDPOAePgFbDCBU0rsOdvWX66C2CPUB2CZM")
        for item in garageList:
            item = os.path.join("garages", item)
            gar = pickle.load(open(item, "rb"))
            g = coder.get(gar.getLocation())
            coords = (g[0].geometry.location.lat, g[0].geometry.location.lng)
            m1 = MapMarker(lat=coords[0], lon=coords[1])
            self.ids.map1.add_marker(m1)
Example #2
0
def geocode_addresses_from_file(list_of_addresses):
    """
    run a list of addresses through the geocoder
    """
    geocoder = GoogleGeocoder()
    f = open("results.txt", "a")
    for address in list_of_addresses:
        try:
            address = address.replace("\n", "")
            search = geocoder.get(address)
        except Exception, exception:
            print "Can't geocode this"
            logger.error("%s" % (exception))
        if len(search) > 0:
            first_result = search[0]
            address_for_output = '%s\t%s\t%s\t%s\t%s\n' % (
                first_result.formatted_address.encode("ascii", "ignore"),
                first_result.geometry.location.lat,
                first_result.geometry.location.lng,
                first_result.geometry.location_type,
                first_result.geometry.partial_match
            )
            print address_for_output
            f.write(address_for_output)
        else:
            print "Can't geocode this"
        time.sleep(3)
Example #3
0
def reverse_geocode(lat, lng):
    geocoder = GoogleGeocoder()
    address = {}
    try:
        search = geocoder.get((lat, lng))[0]
        address = set_fields(search, address)
        address['geocode_status'] = 'success'
    except ValueError, IndexError:
        address['geocode_status'] = 'failed'
Example #4
0
def auto(request):
    f = open('venv/temp.json', 'r+')
    temp = f.read()
    y1 = json.loads(temp)

    print(len(y1["assetHistory"]))
    df1 = json_normalize(y1["assetHistory"])
    df1['serverTimeStamp'] = pd.to_datetime(df1['serverTimeStamp'])
    df1 = df1.set_index('serverTimeStamp')
    df1['eventTimeStamp'] = pd.to_datetime(
        df1['eventTimeStamp'])  # total no of vehicles
    df1 = df1.drop_duplicates(['deviceImeiNo'],
                              keep='first').to_dict('records')
    print(len(df1))
    print(df1[0]["speed"])
    print(type(df1))
    geocoder = GoogleGeocoder("AIzaSyDmXhcX8z4d4GxPxIiklwNvtqxcjZoWsWU")
    y1 = df1

    for i in range(0, 30):
        v1 = vehicle()
        print(i)
        name = names.get_first_name()
        v1.name = name
        speed = str(y1[i]["speed"])
        v1.speed = speed
        latitude = y1[i]["latitude"]
        v1.latitude = latitude
        longitude = y1[i]["longitude"]
        v1.longitude = longitude
        location = geocoder.get((latitude, longitude))
        print(location[0])
        p = str(location[0])
        v1.location = p
        engine = str(y1[i]["engine"])
        v1.engine = engine
        status = str(y1[i]["status"])
        v1.status = status
        odometer = str(y1[i]["odometer"])
        pl = str(y1[i]["plateNumber"])
        v1.plateNumber = pl
        imei = str(y1[i]["deviceImeiNo"])
        v1.deviceImeiNo = imei
        assetid = str(y1[i]["assetId"])
        v1.assetId = assetid
        compid = str(y1[i]["companyId"])
        v1.companyId = compid
        v1.odometer = odometer
        date = str(y1[i]["eventTimeStamp"])
        date = date[0:11]
        v1.date = date
        assetcode = str(y1[i]["AssetCode"])
        v1.assetId = assetcode
        direction = str(y1[i]["direction"])
        v1.direction = direction
        v1.save()
    return render(request, 'main/new.html')
Example #5
0
def lookup_postcode(pc):
    from googlegeocoder import GoogleGeocoder
    geocoder = GoogleGeocoder()

    try:
        search = geocoder.get(pc, region='UK')
    except ValueError:
        return None, None
    res, addr = _make_addr(search)
    return res, addr
Example #6
0
def lookup_postcode(pc):
    from googlegeocoder import GoogleGeocoder
    geocoder = GoogleGeocoder()

    try:
        search = geocoder.get(pc, region='UK')
    except ValueError:
        return None, None
    res, addr = _make_addr(search)
    return res, addr
def submit():
    print('I am inside')
    api = GooglePlaces("YOUR API")
    apii = "YOUR API"
    place = entry_1.get()
    print(place)
    geocoder = GoogleGeocoder(apii)
    search = geocoder.get(place)
    coord = str(search[0].geometry.location.lat)+','+str(search[0].geometry.location.lng)
    places = api.search_places_by_coordinate(coord, "100", variable.get())
    print('I am here')
    fields = ['name', 'formatted_address', 'international_phone_number', 'website', 'rating', 'review']
    for place in places:
        details = api.get_place_details(place['place_id'], fields)
        try:
            website = details['result']['website']
        except KeyError:
            website = ""

        try:
            name = details['result']['name']
        except KeyError:
            name = ""

        try:
            address = details['result']['formatted_address']
        except KeyError:
            address = ""

        try:
            phone_number = details['result']['international_phone_number']
        except KeyError:
            phone_number = ""

        try:
            reviews = details['result']['reviews']
        except KeyError:
            reviews = []
        print("===================PLACE===================")
        print("Name:", name)
        print("Website:", website)
        print("Address:", address)
        print("Phone Number", phone_number)
        print("==================REWIEVS==================")
        for review in reviews:
            author_name = review['author_name']
            rating = review['rating']
            text = review['text']
            time = review['relative_time_description']
            profile_photo = review['profile_photo_url']
            print("Author Name:", author_name)
            print("Rating:", rating)
            print("Text:", text)
            print("Time:", time)
Example #8
0
def extract_bboxes_info(im_name, mask):
    c1 = 35.324992
    c2 = 97.522051
    """Compute centers of bounding boxes from masks.
    mask: [height, width, num_instances]. Mask pixels are either 1 or 0.

    Returns: bbox array [num_instances, (y1, x1, y2, x2)].
    """
    geocoder = GoogleGeocoder("AIzaSyC8J4GIYVFZ4uKtsgXcOfAEZtHMSy-TdEc")
    boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32)
    boxes_loc = np.zeros([mask.shape[-1], 2], dtype=np.int32)
    dict = []
    for i in range(mask.shape[-1]):
        m = mask[:, :, i]
        # Bounding box.
        horizontal_indicies = np.where(np.any(m, axis=0))[0]
        vertical_indicies = np.where(np.any(m, axis=1))[0]
        if horizontal_indicies.shape[0]:
            x1, x2 = horizontal_indicies[[0, -1]]
            y1, y2 = vertical_indicies[[0, -1]]
            # x2 and y2 should not be part of the box. Increment by 1.
            x2 += 1
            y2 += 1
        else:
            # No mask for this instance. Might happen due to
            # resizing or cropping. Set bbox to zeros
            x1, x2, y1, y2 = 0, 0, 0, 0
        boxes[i] = np.array([y1, x1, y2, x2])
        boxes_loc[i] = np.array([int((y1 + y2) / 2), int((x1 + x2) / 2)])

        if ('22' in im_name):
            c1 = 35.322219
            c2 = -97.522901
        elif ('23' in im_name):
            c1 = 35.326396
            c2 = -97.517309
        elif ('24' in im_name):
            c1 = 35.323625
            c2 = -97.517320
        elif ('26' in im_name):
            c1 = 35.325000
            c2 = -97.513532

        lat = -0.007418 / 2736 * float(x1 + x2) / 2.0 + c1
        lon = 0.003970 / 1824 * float(y1 + y2) / 2.0 + c2
        loc = geocoder.get((lat, lon))
        dict.append({
            'lat': lat,
            'lng': lon,
            'address': loc[0].formatted_address
        })

    return dict
def get_coordinates(s): 
    geocoder = GoogleGeocoder(config.get('api-tracker','google_api_key'))
    if s is None :
        return (None,None)
    else:     
        try:
            search = geocoder.get(s)
            if 'locality' in search[0].types:
                return (search[0].geometry.location.lat , search[0].geometry.location.lng)
            else: 
                return (None,None)
        except ValueError: 
            return (None, None)
Example #10
0
    def handle(self, *args, **options):
        geocoder = GoogleGeocoder()

        estabs_to_geocode = GeocodedEstab.objects.filter(latitude=None)
        for estab in estabs_to_geocode:
            print("Address to geocode: %s") % estab.address
            try:
                search = geocoder.get(estab.address)
                time.sleep(1.5)
                estab.latitude = search[0].geometry.location.lat
                estab.longitude = search[0].geometry.location.lng
                print("Latitude: %s, Longitude: %s \n") % (estab.latitude, estab.longitude)
                estab.save()
            except:
                print(("Couldn't geocode."))
def geocoder():
    geocoder = GoogleGeocoder()
    estabs_to_geocode = GeocodedEstab.objects.filter(latitude=None)
    for estab in estabs_to_geocode:
        try:
            #print("Address to geocode: %s") % estab.address
            search = geocoder.get(estab.address)
            time.sleep(1.5)
        except ValueError:
            #print("Couldn't geocode. %d") % (estab.estab_id)
            continue
        estab.latitude = search[0].geometry.location.lat
        estab.longitude = search[0].geometry.location.lng
        #print("Latitude: %s, Longitude: %s \n") % (estab.latitude, estab.longitude)
        estab.save()
        
 def google_address(self, **post):
     res_config = request.env['res.config.settings'].sudo().search(
         [], order="id desc", limit=1)
     script_key = res_config.google_api_key
     data = []
     if ('lat' or 'long') in post:
         lati = post['lat']
         longti = post['long']
         geocoder = GoogleGeocoder(str(script_key))
         geolocator = Nominatim(user_agent=str(script_key))
         # reverse = geocoder.get((lati, longti))
         reverse = geolocator.reverse((lati, longti))
         try:
             data.append(str(reverse[0]))
             if ('emp' and 'attend') in post:
                 attendance_id = request.env['hr.attendance'].sudo().search(
                     [('id', '=', int(post['attend'])),
                      ('employee_id', '=', int(post['emp']))],
                     limit=1)
                 attendance_id.write({
                     'address': str(reverse[0]),
                     'browser': str(post['browser']),
                     'os': str(post['os'])
                 })
         except IndexError:
             return json.dumps([])
     return json.dumps(data)
Example #13
0
def fetch_street_view_image(address: str, geocoder_api_key: str,
                            streetview_api_key: str) -> gsv_api.results:
    """Retrieve StreetView images for the address."""
    geocoder = GoogleGeocoder(geocoder_api_key)
    result = geocoder.get(address)[0]
    params = {
        "size": "600x600",
        "location": result.formatted_address,
        "pitch": "0",
        "key": streetview_api_key,
        "source": "outdoor",
        "fov": "120",
    }
    api_list = gsv_helpers.api_list(params)
    results = gsv_api.results(api_list)
    return results
    def handle(self, *args, **options):
        geocoder = GoogleGeocoder()
        permits = Permit.objects.all()

        for permit in permits:
            if permit.latitude == None and permit.longitude == None:
                try:
                    search = geocoder.get(permit.address)
                    time.sleep(1.5)
                    permit.latitude = search[0].geometry.location.lat
                    permit.longitude = search[0].geometry.location.lng
                    permit.geocode_accuracy = search[0].geometry.location_type
                    print("Latitude: %s, Longitude: %s, Location type: %s") % ( permit.latitude, permit.longitude, permit.geocode_accuracy )
                    permit.save()
                except:
                    print("Couldn't geocode...")
Example #15
0
class ReverseGeoCode():

    def __init__(self):
        self.geocoder = GoogleGeocoder()

    def reverse_geocode_country(self, latitude, longitude):
        country = None
        reverse = None

        attempts = 0
        success = False

        while success != True and attempts < 3:
            try:
                attempts += 1
                reverse = self.geocoder.get((latitude, longitude))
            except:
                time.sleep(1)
                continue

            success = True

        if success == False:
            raise Exception('Error reverse geo-coding the location via Google')

        try:
            address = reverse[0].formatted_address
            address_tokens = address.split()
            country = address_tokens[len(address_tokens) - 1]

        except:
            raise Exception('Error post-processing the Google reverse geocoded location into country')

        return country
Example #16
0
def location_geocode(location, attempt):
    """

    :param location:
    :param attempt:
    :return:
    """
    # initialize Google Geocoder
    geocoder = GoogleGeocoder()

    # location must be a class or subclass of Location
    if isinstance(location.__class__, Location):
        raise ValueError

    location_full_name = location.name + ', San Francisco, CA'

    try:
        logging.info('Geocoding: ' + location_full_name)

        # Get result from Google Maps API
        search = geocoder.get(location_full_name)

        if len(search) > 0:
            logging.info(search[0])
            location.latitude = search[0].geometry.location.lat
            location.longitude = search[0].geometry.location.lng
            db.session.commit()

    except ValueError as error:
        # Get message from error
        msg = str(error)

        if msg == 'OVER_QUERY_LIMIT':
            logging.info('OVER_QUERY_LIMIT, waiting 2 seconds, attempt: ' + str(attempt))
            time.sleep(2)
            if attempt < 3:
                location_geocode(location, attempt + 1)
            else:
                raise Exception('OVER_QUOTA_LIMIT')

        elif msg == 'ZERO_RESULTS':
            logging.warning('No result for: ' + location_full_name)

        else:
            logging.error('Google geocoder : ValueError: ', msg)
Example #17
0
def geocode_a_single_address():
    ''' convert text file of addresses to a list '''
    address = raw_input("Enter an address to geocode ... > ")
    geocoder = GoogleGeocoder()
    try:
        search = geocoder.get(address)
        if len(search) > 0:
            first_result = search[0]
            address_for_output = '%s\t%s\t%s\t%s\t%s\n' % (
                first_result.formatted_address.encode(
                    'ascii', 'ignore'), first_result.geometry.location.lat,
                first_result.geometry.location.lng,
                first_result.geometry.location_type,
                first_result.geometry.partial_match)
            print address_for_output
        else:
            print "Can't geocode this"
    except Exception, exception:
        logger.error("%s" % (exception))
Example #18
0
 def _get_lat_lng_from(self, zip_code):
     """
     """
     zip_code = unicode(zip_code)
     geocoder = GoogleGeocoder()
     try:
         search = geocoder.get(zip_code)
         if len(search) > 0:
             first_result = search[0]
             lat = first_result.geometry.location.lat
             lng = first_result.geometry.location.lng
             return {"lat": lat, "lng": lng}
         else:
             lat = None
             lng = None
             return False
     except Exception, exception:
         logger.error("%s" % (exception))
         return False
Example #19
0
def main(unused_argv):
  logging.basicConfig(level=logging.INFO)
  conn = MySQLdb.connect(host="mysql.anjoola.com", user="******",
                         passwd="pokemon", db="ashaforedu")
  cursor = conn.cursor()
  cursor.execute("SELECT DISTINCT town.id, town.name, district.name FROM town LEFT JOIN district ON (town.district_id = district.id) WHERE town.latitude IS NULL")
  rows = cursor.fetchall()
  for row in rows:
    geocoder = GoogleGeocoder()
    try:
      search = geocoder.get("%s, India" % row[2])
    except ValueError, e:
      logging.info("FAILED %s - %s", row[0], e)
      continue
    name = re.sub(r"'", r"\'", row[1])
    location = search[0].geometry.location
    logging.info("Updating row %s - %s", row[0], name)
    cursor.execute("UPDATE town SET latitude = %s, longitude = %s WHERE "
                   "name = '%s'" % (location.lat, location.lng, name))
    time.sleep(0.05)
Example #20
0
def geocode():
    data = get_raw_data()
    geocoder = GoogleGeocoder()
    outpath = os.path.join(os.path.dirname(__file__), 'data', '2011_geocoded.csv')
    outfile = csv.writer(open(outpath, "w"))
    outfile.writerow(['Name', 'Address', 'Time', 'Date', 'Lat', 'Lng'])
    for row in data:
        address = row.get("Address")
        print address
        search = geocoder.get(address, region='US')
        coords = search[0].geometry.location
        row['lat'], row['lng'] = coords.lat, coords.lng
        outfile.writerow([
            row['Name'],
            row['Address'],
            row['Time'],
            row['Date'],
            row['lat'],
            row['lng'],
        ])
Example #21
0
def geocode_a_single_address():
    ''' convert text file of addresses to a list '''
    address = raw_input("Enter an address to geocode ... > ")
    geocoder = GoogleGeocoder()
    try:
        search = geocoder.get(address)
        if len(search) > 0:
            first_result = search[0]
            address_for_output = '%s\t%s\t%s\t%s\t%s\n' % (
                first_result.formatted_address.encode('ascii', 'ignore'),
                first_result.geometry.location.lat,
                first_result.geometry.location.lng,
                first_result.geometry.location_type,
                first_result.geometry.partial_match
            )
            print address_for_output
        else:
            print "Can't geocode this"
    except Exception, exception:
        logger.error("%s" % (exception))
Example #22
0
def main(unused_argv):
  logging.basicConfig(level=logging.INFO)
  conn = MySQLdb.connect(host="mysql.anjoola.com", user="******",
                         passwd="pokemon", db="ashaforedu")
  cursor = conn.cursor()
  cursor.execute("SELECT DISTINCT district.id, district.name, state.name FROM district JOIN state ON (district.state_id = state.id) WHERE latitude IS NULL")
  rows = cursor.fetchall()
  for row in rows:
    geocoder = GoogleGeocoder()
    query = "%s, %s, India" % (row[1], row[2])
    try:
      search = geocoder.get(query)
    except ValueError, e:
      logging.info("FAILED %s - %s", row[0], e)
      continue
    location = search[0].geometry.location
    logging.info("Updating row %s - %s, %s", row[0], row[1], row[2])
    cursor.execute("UPDATE district SET latitude = %s, longitude = %s WHERE "
                   "id = %s" % (location.lat, location.lng, row[0]))
    time.sleep(0.05)
Example #23
0
 def get(self):
   conn = MySQLdb.connect(host="mysql.anjoola.com", user="******",
                          passwd="pokemon", db="ashaforedu")
   cursor = conn.cursor()
   cursor.execute("SELECT DISTINCT id, name FROM town WHERE latitude IS NULL")
   rows = cursor.fetchall()
   self.response.write("%s rows returned.<br>\n" % len(rows))
   for row in rows:
     geocoder = GoogleGeocoder()
     try:
       search = geocoder.get("%s, India" % row[1])
     except ValueError, e:
       self.response.write("%s: FAILED - %s<br>\n" % (row[1], e))
       continue
     name = re.sub(r"'", r"\'", row[1])
     location = search[0].geometry.location
     self.response.write("%s: %s<br>\n" % (name, location))
     logging.info("Updating row %s - %s", row[0], name)
     cursor.execute("UPDATE town SET latitude = %s, longitude = %s WHERE "
                    "name = '%s'" % (location.lat, location.lng, name))
     time.sleep(0.05)
    def handle(self, *args, **options):
        geocoder = GoogleGeocoder()
        appraisals_to_geocode = AppraisalData.objects.filter(latitude = None).order_by('id')

        for start, end, total, qs in batch_qs(appraisals_to_geocode):
            print "Now processing %s - %s of %s" % (start +1, end, total)
            
            for appraisal in qs:
                if appraisal.latitude == None and appraisal.longitude == None:

                    st_num = appraisal.situs_num.strip()
                    st_pref = appraisal.situs_street_prefix.strip()
                    street = appraisal.situs_street.strip()
                    str_suf = appraisal.situs_street_sufix.strip()
                    st_zip = ''

                    if appraisal.situs_zip != 'N/A':
                        st_zip = appraisal.situs_zip.strip()

                    city = appraisal.city
                    state = appraisal.situs_state
                    just_city = ''
                    
                    if re.search('(?<=CITY OF).*', city) is not None:
                        just_city = re.search('(?<=CITY OF).*', city).group(0).strip()

                    addy = "%s %s %s %s, %s, %s %s" % (st_num, st_pref, street, str_suf, just_city, state, st_zip)
                    print(addy)

                    try:
                        search = geocoder.get(addy)
                        time.sleep(1.5)
                        appraisal.latitude = search[0].geometry.location.lat
                        appraisal.longitude = search[0].geometry.location.lng 
                        appraisal.geocode_accuracy = search[0].geometry.location_type
                        print("Latitude: %s, Longitude: %s, Location type: %s") % (appraisal.latitude, appraisal.longitude, appraisal.geocode_accuracy)
                        appraisal.save()
                    except: 
                        print(("Couldn't geocode or already geocoded."))
Example #25
0
def multithreading_data_enrichment_with_address(output_folder: str, df: DataFrame, n_threads: int) -> None:
    """
    Do hotels data enrichment with address in terms of concurrency.
    :param output_folder: Path to save data results.
    :param df: Pandas dataframe with data.
    :param n_threads: Amount of threads for task execution concurrently.
    :return: Pandas dataframe with enriched hotels data with address.
    """
    geocoder = GoogleGeocoder(os.environ.get("API_KEY")) or "No access to API_KEY"
    with ThreadPoolExecutor(max_workers=n_threads) as pool:
        df = df.assign(Address=df.apply(lambda row: (row["Latitude"], row["Longitude"]), axis=1)
                       .apply(lambda coordinates: pool.submit(geocoder.get, coordinates))
                       .apply(lambda future_result: future_result.result()[0]))
    hotels_city_data_split_by_100_before_save(output_folder, df)
Example #26
0
class Extractor(Singleton):
    """Class for extracting relevant climate data given an address or lat/long"""

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

    def __init__(self) -> None:
        Singleton.__init__(self)

        self.geocoder = GoogleGeocoder(CONFIG.GEO_CODER_API_KEY)

    def coordinates_from_address(self, address: str) -> Coordinates:
        """Find the lat and lng of a given address"""
        result = self.geocoder.get(address)
        return Coordinates(lat=result[0].geometry.location.lat,
                           lon=result[0].geometry.location.lng)

    def metadata_for_address(self, address: str) -> ClimateMetadata:
        """Calculate climate metadata for a given address"""
        coords = self.coordinates_from_address(address)
        try:
            water_level, shift, rp, flood_risk = fetch_climate_data(address)
        except IndexError:
            water_level = "0"
        return ClimateMetadata(water_level=water_level)
Example #27
0
import urllib.request
import requests
import json
import googlemaps
import math
from geopy.geocoders import Nominatim
from googlegeocoder import GoogleGeocoder

endpoint = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'API_KEY_HERE'
geocoder = GoogleGeocoder(api_key)

origin = input('Where are you?: ').replace(' ', '+')

geolocator = Nominatim(user_agent="capstone")
location = geolocator.geocode("3783 Penderwood Dr")
print(location.address)
print((location.latitude, location.longitude))

#gmaps = googlemaps.Client(api_key)
#geocode_result = gmaps.geocode(origin)
#local = gmaps.local_search('hospital near ' + origin)
#lat = geocode_result[0].geometry.location.lat()
#print(geocode_result)

#destination = input('Where do you want to go?: ').replace(' ','+')

#nav_request = 'origin={}&destination={}&key={}'.format(origin,destination,api_key)
#request = endpoint + nav_request
#response = urllib.request.urlopen(request).read()
Example #28
0
from collections import namedtuple
import re

from lxml import etree

from googlegeocoder import GoogleGeocoder
from slugify import slugify
from pybikes.utils import PyBikesScraper
from pybikes.domoblue import Domoblue

MAIN = 'http://clientes.domoblue.es/onroll/'
TOKEN_URL = 'generaMapa.php?cliente={service}&ancho=500&alto=700'
XML_URL = 'generaXml.php?token={token}&cliente={service}'
TOKEN_RE = 'generaXml\.php\?token\=(.*?)\&cliente'

geocoder = GoogleGeocoder()

CityRecord = namedtuple('CityRecord', 'city, country, lat, lng')

description = 'Extract DomoBlue instances from the main site'

parser = argparse.ArgumentParser(description=description)

parser.add_argument('-o',
                    metavar="file",
                    dest='outfile',
                    default=None,
                    help="Save output to the specified file")
parser.add_argument('-g',
                    '--geocode',
                    action="store_true",
Example #29
0
 def __init__(self):
     self.geocoder = GoogleGeocoder()
Example #30
0
import folium

from googlegeocoder import GoogleGeocoder
geocoder = GoogleGeocoder("<Insert Google Maps API Key Here>")

symbols = {
    "fire": ["fire", "red"],
    "medical": ["plus-sign", "lightblue"],
    "food": ['cutlery', "green"],
    "shelter": ['home', 'beige']
}

data = {
    '1727 E 107th St, Los Angeles, CA': ["fire", "burning flames"],
    '9500 Gilman Dr, La Jolla, CA 92093': ["medical", "needs insulin"],
    '12174 Carmel Mountain Rd, San Diego, CA 92128':
    ['shelter', "no place to sleep tonight"],
    '880 Summit Blvd, Big Bear Lake, CA 92315':
    ['food', "ran out of food yesterday"],
}

#creating a map with default view in United States
m = folium.Map(location=[39.00, -98.21], zoom_start=5)

#creating markers based on data from NLP database
for key, value in data.items():
    emergency = geocoder.get(key)
    lat = emergency[0].geometry.location.lat
    lng = emergency[0].geometry.location.lng
    folium.Marker([lat, lng],
                  popup=value[1],
Example #31
0
def CHSMAP():

    storage_client = storage.Client()

    GeocodeToken = json.loads(
        storage_client.get_bucket("hc_tokens_scripts").get_blob(
            "Tokens/Google Keys.json").download_as_string())['Keys'][0]["Key"]

    geocoder = GoogleGeocoder(GeocodeToken)

    scope = [
        "https://spreadsheets.google.com/feeds",
        "https://www.googleapis.com/auth/spreadsheets",
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/drive"
    ]

    credraw = storage_client.get_bucket('hc_tokens_scripts').blob(
        'Tokens/hireclix-googlesheets.json').download_as_string()

    credjson = json.loads(credraw)

    cred = ServiceAccountCredentials.from_json_keyfile_dict(credjson, scope)

    gclient = gspread.authorize(cred)

    sheet = gclient.open_by_key('1QelQJlQBTEWC_YY_t0Zmh7CIfn1WG714DqidJ3TW5Rw'
                                ).worksheet('CHS Expansion Status')

    items = sheet.get_all_values()

    jsonobject = {
        "type": "FeatureCollection",
        "name": "Points_2",
        "crs": {
            "type": "name",
            "properties": {
                "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        },
        "features": []
    }

    for item in items:
        if item == items[0]:
            continue
        if item[2] != "":
            search = geocoder.get(item[2])
            new = {
                "type": "Feature",
                "properties": {
                    "Hospital": item[0],
                    "City": re.sub(",.*$", "", item[1]),
                    "State": re.sub("^.*, ", "", item[1]),
                    "Address": item[2],
                    "POC": re.sub("\\n", ", ", item[3]),
                    "Status": item[4],
                    "Notes": item[5],
                    "Latitude": search[0].geometry.location.lat,
                    "Longitude": search[0].geometry.location.lng
                },
                "geometry": {
                    "type":
                    "Point",
                    "coordinates": [
                        search[0].geometry.location.lng,
                        search[0].geometry.location.lat
                    ]
                }
            }
            jsonobject['features'].append(new)

    print("var json_Points_2 = " + json.dumps(jsonobject))
    with gcsfs.GCSFileSystem(project="hireclix").open("chs_map/Points_2.js",
                                                      "w") as fl:
        fl.write("var json_Points_2 = " + json.dumps(jsonobject))
        fl.close()
Example #32
0
for line in rows:
	allProviders.append(make_provider(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], "NULL", "NULL"))

#removes first header Provider
allProviders.pop(0)

#iterates through states
#uses dictionary to convert to Abbrev
for provider in allProviders:
	for x in stateAbbrev.states:
		if provider.state in stateAbbrev.states[x]:
			provider.state = x


#Google Geocoder finds lat & long
geocoder = GoogleGeocoder()
geospacial = ""
for provider in allProviders:
	address = provider.address_1 + " "+ provider.city + " " +  provider.state 
	#print address
	time.sleep(2)
	search = geocoder.get(address)
	geospacial = (search[0].geometry.location.lat, search[0].geometry.location.lng)
	geospacial = str(geospacial)
	geospacial = re.sub(r'[()]+', '', geospacial)
	geospacial = geospacial.split(',')
	provider.latitude = geospacial[0].strip()
	provider.longitude = geospacial[1].strip()
	#print provider.latitude
	#print provider.longitude
Example #33
0
    def __init__(self) -> None:
        Singleton.__init__(self)

        self.geocoder = GoogleGeocoder(CONFIG.GEO_CODER_API_KEY)
Example #34
0
 if len(qs[:]) > 0:
     h = qs[:1].get()
 else:
     h.hotelName = location_name  #Because the format of the variables is byte, they must be converted to strings or ints/floats
     #h.city = str(city)
     h.address = str(address)
     h.geometry = None
     if len(mapcontainer) > 0:
         print("Trial")
         h.geometry = [
             float(mapcontainer[0].get('data-lng')),
             float(mapcontainer[0].get('data-lat'))
         ]
     else:
         try:
             geolocator = GoogleGeocoder()
             geolocation = None
             for coords in geolocator.get(h.address):
                 if (geo.checkCoordinate(coords.geometry.location.lng,
                                         coords.geometry.location.lat)):
                     geolocation = coords
             print("Google")
             print(geolocation.geometry.location.lng)
             h.geometry = [
                 geolocation.geometry.location.lng,
                 geolocation.geometry.location.lat
             ]
         except Exception:
             print(h.address + "Address cannot be located")
     print(h.geometry)
     h.save()
Example #35
0
import googlemaps
import os
import requests

folder_path = r'F:\Upwork\Geo-cordiantes mapping and distance calculation'
excel_file_name = "Watewater UPS Sites- WRE List.xlsx"
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

data = pd.read_excel(os.path.join(folder_path, excel_file_name))
data["longitude"] = 0.000000000000000000000000000
data["lattitude"] = 0.000000000000000000000000000
data["Cordinates"] = None

i = 0
for i in range(0, len(data)):
    geocoder = GoogleGeocoder(API_KEY)
    try:
        #search = geocoder.get(data["Location"][i])#+ " " + data["City"][i]+ " " + data["State"][i])
        search = geocoder.get(data["Address"][i] + " " + data["City"][i] +
                              " " + data["State"][i])
        cord = search[0].geometry.location
        data.loc[i, "Cordinates"] = cord
        cord_list = str(cord).split(',')
        lattitude = cord_list[0].replace('(', '')
        lattitude = lattitude.replace(')', '')
        lattitude = lattitude.replace(' ', '')

        longitude = cord_list[1].replace(')', '')
        longitude = longitude.replace("'", '')
        longitude = longitude.replace(' ', '')
Example #36
0
## Installation of python libraries:
##		GoogleGeocoder: pip install python-googlegeocoder
##		Google Streetview API: pip install google_streetview
#######################################################################
import os
import sys

from googlegeocoder import GoogleGeocoder
import google_streetview.api

google_key = "<google maps api key>"

search = sys.argv[1:]
search_addr = ",".join(search)

geocoder = GoogleGeocoder(google_key)

location = geocoder.get(search_addr)
location = location[0]
print('Address of ', search_addr, ' is ', location.formatted_address)

loc_lat = location.geometry.location.lat
loc_lng = location.geometry.location.lng

print('Latitude and Longitudes of ', search_addr, ' are ', [loc_lat, loc_lng])

loc_lat_lng = [loc_lat, loc_lng]
loc_lat_lng = ",".join(map(str, loc_lat_lng))
loc = str(loc_lat_lng)

params = {
 ranks = soup3.findAll('b', {"class", "rank_text"})
 qs=TAHotel.objects.filter(hotelName=location_name)
 h = TAHotel()
 if len(qs[:])>0:
     h=qs[:1].get()
 else:
     h.hotelName = location_name #Because the format of the variables is byte, they must be converted to strings or ints/floats
     #h.city = str(city)
     h.address = str(address)
     h.geometry=None
     if len(mapcontainer)>0:
         print("Trial")
         h.geometry=[float(mapcontainer[0].get('data-lng')),float(mapcontainer[0].get('data-lat'))]
     else:
         try:
             geolocator = GoogleGeocoder()
             geolocation=None
             for coords in geolocator.get(h.address):
                 if(geo.checkCoordinate(coords.geometry.location.lng,coords.geometry.location.lat)):
                     geolocation =coords
             print("Google")
             print(geolocation.geometry.location.lng)
             h.geometry=[geolocation.geometry.location.lng,geolocation.geometry.location.lat]
         except Exception:
             print(h.address+"Address cannot be located")
     print(h.geometry)
     h.save()
 for review, rating, user, quote in zip(adjreviews, ratings, users, quotes):
     r = HotelReview()
     r.review = str(review.text)
     #r.rating = int(str(rating)[2])
Example #38
0
import csv
import time
from googlegeocoder import GoogleGeocoder

geocoder = GoogleGeocoder()

with open("/Users/kschwen/Dev/personal/ona-mapping-talk/project/data/raw_inspections.csv", "r") as f:
    data = list(csv.reader(f))

with open("/Users/kschwen/Dev/personal/ona-mapping-talk/project/data/geocoded_inspections.csv", "w") as f:
    writer = csv.writer(f)
    for row in data:
        # Full address are the 3 columns after the first.
        full_address = "%s, %s, CA, %s" % (row[1], row[2], row[3])
        try:
            search = geocoder.get(full_address)
            row.append(search[0].geometry.location.lat)
            row.append(search[0].geometry.location.lng)
            print row
            writer.writerow(row)
            time.sleep(.5)
        except:
            print "Couldn't geocode ", row
Example #39
0
# from pygeocoder import Geocoder
from googlegeocoder import GoogleGeocoder

import csv, time

addrfile = open("addr.csv", "r")
stop_time_for_geocoder = 0.1  # old 0.25

reader = csv.reader(addrfile)
allRows = [row for row in reader]
geocoder = GoogleGeocoder()

for address in allRows:

    try:
        search = geocoder.get(str(address)[1:-1])
        print search[0].formatted_address + "^" + str(search[0].geometry.location) + "^" + str(
            search[0].geometry.location_type
        )

    except:
        print "bad address"

    time.sleep(stop_time_for_geocoder)
Example #40
0
## HELPER PYTHON SCRIPT I WROTE TO GENEREATE LONGITUDE AND LATITUDE BY USING GOOGLE API

from googlegeocoder import GoogleGeocoder
import csv

geocoder = GoogleGeocoder("TOKEN GO HERE")
visited = set()
rawData = []

states_hash = {
    'Alabama': 'AL',
    'Alaska': 'AK',
    'Arizona': 'AZ',
    'Arkansas': 'AR',
    'California': 'CA',
    'Colorado': 'CO',
    'Connecticut': 'CT',
    'Delaware': 'DE',
    'District Of Columbia': 'DC',
    'Florida': 'FL',
    'Georgia': 'GA',
    'Guam': 'GU',
    'Hawaii': 'HI',
    'Idaho': 'ID',
    'Illinois': 'IL',
    'Indiana': 'IN',
    'Iowa': 'IA',
    'Kansas': 'KS',
    'Kentucky': 'KY',
    'Louisiana': 'LA',
    'Maine': 'ME',
Example #41
0
import pandas as pd
import numpy as np
from googlegeocoder import GoogleGeocoder
geocoder = GoogleGeocoder("")

#Define key variables with their weighted values
fml = 0.2
geo = 0.2
occ = 0.2
tra = 0.2
sym = 0.2

#Geographic Centers
centers = [114.23724199, 114.13673885, 113.97385556, 114.17992336]

print(
    'Welcome to the COVID-19 Epidemiology based risk classifer. \nWe aim to provide an assesment for the risk score based on \n1.geographic location\n2.family ties\n3.occupation\n4.travel history\n'
)

#Step 1: Calculating the spatial distance from key clusters
add = input('Please enter your Address in Hong Kong\n>')
add = add + " Hong Kong"
try:
    search = geocoder.get(add)
except ValueError:
    search = 'Hong Kong'
lat = float(search[0].geometry.location.lat)
long = float(search[0].geometry.location.lng)
dist = []
for i in centers:
    dist.append(abs(i - long))
Example #42
0
def getlatlong(address):
    geocoder = GoogleGeocoder("Google-Map-api-keys-xxxxxxxxxxxxx")
    search = geocoder.get(address)
    return (search[0].geometry.location.lat, search[0].geometry.location.lng)
Example #43
0
def CHSMAP():

    storage_client = storage.Client()

    GeocodeToken = json.loads(storage_client.get_bucket("hc_tokens_scripts")
                              .get_blob("Tokens/Google Keys.json")
                              .download_as_string())['Keys'][0]["Key"]

    geocoder = GoogleGeocoder(GeocodeToken)

    scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets",
             "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]

    credraw = storage_client.get_bucket('hc_tokens_scripts').blob(
        'Tokens/hireclix-googlesheets.json').download_as_string()

    credjson = json.loads(credraw)

    cred = ServiceAccountCredentials.from_json_keyfile_dict(credjson, scope)

    gclient = gspread.authorize(cred)

    sheet = gclient.open_by_key('1QelQJlQBTEWC_YY_t0Zmh7CIfn1WG714DqidJ3TW5Rw').worksheet('CHS Expansion Status')

    newpoints = sheet.get_all_values()

    with gcsfs.GCSFileSystem(project="hireclix").open("chs_map/Points_2.js", "r") as fl:
        prevpointsraw = fl.read()[20:]


    prevpoints = json.loads(prevpointsraw)

    newpointsinter = iter(newpoints)
    next(newpointsinter)

    for newpoint in newpointsinter:
        flag = 0
        if newpoint[0] == "" or newpoint[2] == "":
            continue
        for prevpoint in prevpoints['features']:
            if prevpoint['properties']['Hospital'] == newpoint[0]:
                prevpoint['properties']['POC'] = re.sub("\\n", ", ", newpoint[3])
                prevpoint['properties']['Status'] = newpoint[4]
                prevpoint['properties']['Notes'] = newpoint[5]
                if prevpoint['properties']['Address'] != newpoint[2]:
                    search = geocoder.get(newpoint[2])
                    prevpoint['properties']['City'] = re.sub(",.*$", "", newpoint[1])
                    prevpoint['properties']['State'] = re.sub("^.*, ", "", newpoint[1])
                    prevpoint['properties']['Address'] = newpoint[2]
                    prevpoint['properties']['Latitude'] = search[0].geometry.location.lat
                    prevpoint['properties']['Longitude'] = search[0].geometry.location.lng
                    prevpoint['geometry']['coordinates'] = [search[0].geometry.location.lng,
                                                            search[0].geometry.location.lat]
                flag = 1
                break
        if flag == 1:
            continue
        elif flag == 0:
            search = geocoder.get(newpoint[2])
            new = {
                "type": "Feature",
                "properties": {
                    "Hospital": newpoint[0],
                    "City": re.sub(",.*$", "", newpoint[1]),
                    "State": re.sub("^.*, ", "", newpoint[1]),
                    "Address": newpoint[2],
                    "POC": re.sub("\\n", ", ", newpoint[3]),
                    "Status": newpoint[4],
                    "Notes": newpoint[5],
                    "Latitude": search[0].geometry.location.lat,
                    "Longitude": search[0].geometry.location.lng
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        search[0].geometry.location.lng,
                        search[0].geometry.location.lat
                    ]
                }
            }

            prevpoints['features'].append(new)

    print(prevpoints)
    raise KeyboardInterrupt
    with gcsfs.GCSFileSystem(project="hireclix").open("chs_map/Points_2.js", "w") as fl:
        fl.write("var json_Points_2 = " + json.dumps(prevpoints))
        fl.close()
## the database, we'll need to try geocoding it through Google, and if that
## doesn't work we'll go through Geocoder.US, and if that doesn't work
## we'll give it the site of the 1903 RMS Republic wreck for no reason
## whatsoever.
## If we do have a single listing, let's grab the lat and long.
## If we have multiple listings for the same address, we probably have
## database corruption.

        geodb.execute('select count(*), glat, glong from sexgeo where fulladdy = ?', [fulladdy])
        sqlreturn = geodb.fetchone()
    #    print sqlreturn
        if sqlreturn[0] == 0:
            try:
                #county in line[14], needs to be upper, matched
                
                geocoder = GoogleGeocoder()
                search = geocoder.get(fulladdy)
                glat=str(search[0].geometry.location.lat)
                glong=str(search[0].geometry.location.lng)
            except (ValueError, GQueryError):
# HEY CHECK ERROR CONDITIONS
                    print "Location '", fulladdy, "not found. Setting lat-long to 42.02,-42.02, in honor of OCGA 42 1 12"
                    glat = errorlat
                    glong = errorlong
                    gplace = "OCGA 42-1-12 calls for registry, but we can't find this person."
    ## So if things went right, we now have a geocoded address.
    ## Let's put that in the database.                
            geodb.execute('insert into sexgeo values (?,?,?)', [fulladdy, glat, glong])
#            geodbconn.commit()
## Uncomment the above line to record lat-longs as we find them, at the cost of speed
            print line[0], ": geocoded and recorded ", fulladdy, "at ", glat, ", ", glong