Example #1
0
 def get_reverse_geo(self,fileWithCoords):
     from pygeocoder import Geocoder # sudo port select python python26
     #fileWithAddresses='/Users/admin/Desktop/work_locations.txt'
     f=open(fileWithCoords,'r')
     x=f.read()
     f.close()
     z=x.split('\r')
     pt=0
     for i in range(0,len(z)):
         a=z[i].split('\t')
         print Geocoder.reverse_geocode(eval(a[0]),eval(a[1]))
         pt+=1
         if pt==10:
             sleep(10)
             pt=0
Example #2
0
 def get_reverse_geo(self, fileWithCoords):
     from pygeocoder import Geocoder  # sudo port select python python26
     #fileWithAddresses='/Users/admin/Desktop/work_locations.txt'
     f = open(fileWithCoords, 'r')
     x = f.read()
     f.close()
     z = x.split('\r')
     pt = 0
     for i in range(0, len(z)):
         a = z[i].split('\t')
         print Geocoder.reverse_geocode(eval(a[0]), eval(a[1]))
         pt += 1
         if pt == 10:
             sleep(10)
             pt = 0
Example #3
0
    def test_reverse_geocode(self):
        """
        Test pygeocoder reverse_geocode()

        """
        lat, lng = 38.897096, -77.036545
        result = Geocoder.reverse_geocode(lat, lng)

        self.assertEqual(result.country__short_name, 'US')
        self.assertEqual(result.postal_code, '20500')
        self.assertEqual(result.street_number, '1600')
        self.assertEqual(result.route, 'Pennsylvania Avenue Northwest')
        self.assertEqual(result.administrative_area_level_1, 'District of Columbia')
        self.assertEqual(result.city, 'Washington, D.C.')
        self.assertEqual(result.state, 'District of Columbia')
        self.assertEqual(result.state__short_name, 'DC')
        self.assertEqual(result.country, 'United States')
        addr = result.formatted_address
        self.assertEqual(addr, "1600 Pennsylvania Avenue Northwest, President's Park, Washington, D.C., DC 20500, USA")
        lat2, lng2 = result.coordinates
        self.assertAlmostEqual(lat, lat2, 3)
        self.assertAlmostEqual(lng, lng2, 3)
        self.assertAlmostEqual(lat, result.latitude, 3)
        self.assertAlmostEqual(lng, result.longitude, 3)
        self.assertTrue(result.count > 1)
Example #4
0
def geocode():
    input_type = raw_input(
        'Are you hoping to geocode addresses or coordinates?\nEnter Addresses or Coordinates: '
    )
    results = []
    estab_df = promptFilePath()
    if input_type == 'Addresses':
        print 'Fetching coordinates...'
        for a in estab_df["Address"]:
            time.sleep(0.25)
            results.append(list(geo.geocode(a).coordinates))
        geocoded_estab_df = estab_df.join(
            pd.DataFrame(results, columns=['Latitude', 'Longitude']))
    elif input_type == 'Coordinates':
        print 'Fetching addresses...'
        for i, c in estab_df.iterrows():
            time.sleep(0.25)
            results.append(
                list(
                    geo.reverse_geocode(estab_df.Latitude[i],
                                        estab_df.Longitude[i])))
        geocoded_estab_df = estab_df.join(
            pd.DataFrame(results, columns=['Address']))
    else:
        print 'Please only select Addresses or Coordinates.'
        return
    return geocoded_estab_df
Example #5
0
def google_geotag_file(ifile):
    print "\nGoogle:"
    file_phi_psi = get_lat_long_file(ifile)
    location = Geocoder.reverse_geocode(math.degrees(file_phi_psi.latitude()), math.degrees(file_phi_psi.longitude()))
    admin = "administrative_area_level_"
    location_attributes = list()
    location_attributes.append(["country",           "Country          ","-country="])
    location_attributes.append([admin + "1",         "State            ","-state="])
    location_attributes.append(["locality",          "City             ","-city="])
    location_attributes.append(["postal_code",       "Zip Code         ", "-Keywords+="])
    location_attributes.append(["neighborhood",      "Neighborhood     ", "-Keywords+="]) # UWS
    location_attributes.append(["political",         "City?            ", ""]) # great falls/uws
    location_attributes.append([admin + "2",         "County           ", ""]) # county
    location_attributes.append([admin + "3",         "District         ", ""]) # district?
    location_attributes.append(["sublocality",       "Sublocality      ", ""]) # manhattan
    location_attributes.append(["airport",           "Airport          ", ""])
    location_attributes.append(["park",              "Park             ", ""])
    location_attributes.append(["natural_feature",   "Natural Feature  ", ""])
    location_attributes.append(["point_of_interest", "Point of Interest", ""])
    location_attributes.append(["street_address",    "Street Address   ", ""])
    location_attributes.append(["route",             "Road             ", ""])
    location_attributes.append(["intersection",      "Intersection     ", ""])
    location_attributes.append(["colloquial_area",   "Colloquial Area  ", ""])
    location_attributes.append(["premise",           "Premise          ", ""])
    location_attributes.append(["subpremise",        "Subpremise       ", ""])

    for i in location_attributes[:5]:
        this_attr = getattr(location[0], i[0])
        if(this_attr != None):
            print i[1], "\t", this_attr
def coordinate_generator(number_of_points):
   
    coordinate_list = []
    counter = 0
    geocoder = Geocoder()

    while counter < number_of_points:
        lat = round(random.uniform(SOUTHERNMOST, NORTHERNMOST), 6)
        lng = round(random.uniform(EASTERNMOST, WESTERNMOST), 6)
        try:
            gcode = geocoder.reverse_geocode(lat, lng)

            if gcode[0].data[0]['formatted_address'][-6:] in ('Canada', 'Mexico'):
                continue
            elif 'unnamed road' in gcode[0].data[0]['formatted_address']:
                continue
            elif 'Unnamed Road' in gcode[0].data[0]['formatted_address']:
                continue
            else:
                counter += 1
                #coordinate_list.append((gcode[0].coordinates, gcode[0].formatted_address))
                coordinate_list.append(gcode[0].coordinates)
            # output_file.write(fullstring.format(gcode.x, gcode.y, gcode.address))
        except GeocoderError:
            continue
    print('Finished generating %d coordinate points' % counter)
    return coordinate_list
def coordinate_generator(number_of_points):
    """
    Generate a number of random geographical points and then geocode them.

    :param number_of_points: number of points to generate
    :type number_of_points: int
    :return: list of geographic point tuples

    """

    coordinate_list = []
    counter = 0
    geocoder = Geocoder()

    while counter < number_of_points:
        lat = round(random.uniform(SOUTHERNMOST, NORTHERNMOST), 6)
        lng = round(random.uniform(EASTERNMOST, WESTERNMOST), 6)
        try:
            gcode = geocoder.reverse_geocode(lat, lng)

            if gcode[0].data[0]['formatted_address'][-6:] in ('Canada', 'Mexico'):
                continue
            elif 'unnamed road' in gcode[0].data[0]['formatted_address']:
                continue
            elif 'Unnamed Road' in gcode[0].data[0]['formatted_address']:
                continue
            else:
                counter += 1
                coordinate_list.append((gcode[0].coordinates, gcode[0].formatted_address))
            # output_file.write(fullstring.format(gcode.x, gcode.y, gcode.address))
        except GeocoderError:
            continue
    print 'Finished generating %d coordinate points' % counter
    return coordinate_list
def detectCountry(lat, lng):
    #url_geo = "http://ws.geonames.org/countryCode?lat=%s&lng=%s" %(lat,lng)
    print "Detecting: ", lat, lng
    results = Geocoder.reverse_geocode(lat, lng)
    if "Brazil" == results:
        results = "Brasil"
    return results[0].country
Example #9
0
def getUserLocation(latd, lond):
    """
    Get users location given the coordinates
    Uses pygeocoder, a python interface for Google Geocoding API V3
    Given the lat, lon it reverse geocodes location

    ToDO - Still returns null in the dataset
    need a way to handle it

    BLOCKED!!!

    """
    print latd, lond
    if latd != None and lond != None:
        try:
            location = geo.reverse_geocode(latd, lond)
        except GeocoderError:  # catch the exceptions you know!
            print '***********************************************'
            return 'Patagonia'
        except UnicodeEncodeError:
            print '***********************************************'
            return 'Patagonia'
        else:
            if location != None:
                return location.city
            else:
                return 'Patagonia'
    else:
        return 'Patagonia'
Example #10
0
def address_from_latlong(latitude, longitude):
    """Get human-readable address from (lat, long) location."""
    try:
        return Geocoder.reverse_geocode(latitude,longitude)[0]
    except GeocoderError, e:
    	print "Error when converting address to (lat,long): %s" % e
        return ''
Example #11
0
    def clean(self):
        cleaned_data = super(PointImportForm, self).clean()
        lat, lon = cleaned_data.get('latitude'), cleaned_data.get('longitude')

        # point geometry
        geometry = cleaned_data.get('geometry')
        if not geometry:
            if not all((lat, lon)):
                raise forms.ValidationError(
                    'Geometry fields require latitude and longitude')
            geometry_field = self.fields['geometry']
            pnt = geos.Point(lon, lat, srid=geometry_field.srid)
            cleaned_data['geometry'] = geometry_field.clean(pnt)

        # zipcode geocode
        zipcode = cleaned_data.get('zip')
        if not zipcode:
            if not all((lat, lon)):
                raise forms.ValidationError(
                    'Zipcode fields require latitude and longitude')

            key = hash((lat, lon))
            result_data = self._cache.get(key)
            if result_data:
                result = GeocoderResult(result_data)
            else:
                result = Geocoder.reverse_geocode(lat=lat, lng=lon)
                self._cache.set(key, result.data)

            zipcode = result[0].postal_code
            cleaned_data['zip'] = self.fields['zip'].clean(zipcode)
        return cleaned_data
def get_rev_address(lat, lng,method="geopy", district_only=False):
	string=lat+','+lng
	if 'geopy' in method:
		location = geolocator.reverse(string)
		return location.address
	else:
		lat=float(lat)
		lng=float(lng)
		#print str(lat)+" , "+  str(lng)

		results=""
		try:
			rs=Geocoder.reverse_geocode(lat,lng)
		
		except:
			results=""
		try:	
			results+="city:"
			results+=rs.city
		except:
			results+=""

		try:	
			results+=",district:"
			results+=rs.county
		except:
			results+=""
		try:
			results+=",raw:"+rs.__str__()
		except:
			results+=""

		if district_only:
			return rs.county
		return results
Example #13
0
    def clean(self):
        cleaned_data = super(PointImportForm, self).clean()
        lat, lon = cleaned_data.get('latitude'), cleaned_data.get('longitude')

        # point geometry
        geometry = cleaned_data.get('geometry')
        if not geometry:
            if not all((lat, lon)):
                raise forms.ValidationError('Geometry fields require latitude and longitude')
            geometry_field = self.fields['geometry']
            pnt = geos.Point(lon, lat, srid=geometry_field.srid)
            cleaned_data['geometry'] = geometry_field.clean(pnt)

        # zipcode geocode
        zipcode = cleaned_data.get('zip')
        if not zipcode:
            if not all((lat, lon)):
                raise forms.ValidationError('Zipcode fields require latitude and longitude')

            key = hash((lat, lon))
            result_data = self._cache.get(key)
            if result_data:
                result = GeocoderResult(result_data)
            else:
                result = Geocoder.reverse_geocode(lat=lat, lng=lon)
                self._cache.set(key, result.data)

            zipcode = result[0].postal_code
            cleaned_data['zip'] = self.fields['zip'].clean(zipcode)
        return cleaned_data
Example #14
0
def sos():
    data = json.loads(request.data)
    name = data.get('name').upper()
    lat = data.get('lat')
    lng = data.get('lng')
    description = data.get('description')
    feed = Feed.query.filter(Feed.name==name, Feed.lat==lat, Feed.lng==lng,
                             Feed.state=='open').first()
    result = None
    if not feed:
        try:
            address = Geocoder.reverse_geocode(float(lat), float(lng))[0]
            new_feed = Feed(name=name, lat=lat, lng=lng, address=address,
                description=description)
            db_session.add(new_feed)
            db_session.commit()
            result = {
                'id': new_feed.id,
                'lat': new_feed.lat,
                'lng': new_feed.lng,
                'createdAt':
                    new_feed.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
                'name': new_feed.name,
                'description': new_feed.description,
                'state': new_feed.state
            }
        except:
            result = { 'error_msg': 'DB Error' }
        finally:
            db_session.remove()
    else:
        result = {
            'error_msg': 'Entry exists.'
        }
    return jsonify(result)
def get_happiest_state(tweet_stream):
  elements = {}

  tweets_stream_file = open(tweet_stream)
  for tweets_lines in tweets_stream_file:
    # load the json data of tweet streams
    tweetJSON=json.loads(tweets_lines)
    #print tweetJSON
    # iterate over each data in each tweets
    for (key, value) in tweetJSON.items():
      initial_score=1

      ##  Analysing the user's location data against the cities in the United States
      #'''
      # using the geocoder from google map api (http://code.xster.net/pygeocoder/wiki/Home)
      if key == 'coordinates' and tweetJSON['coordinates'] is not None:
        geo_coordinate = value['coordinates'];
        longitude = geo_coordinate[0]
        latitude =  geo_coordinate[1]
        location=Geocoder.reverse_geocode(latitude, longitude)
        print location

    #https://dev.twitter.com/docs/platform-objects/tweets
      # using the place hash in the tweet stream
      elif key == 'place' and tweetJSON['place'] is not None:
        if value["country"] == "United States" or value["country_code"] == "US":
         # print value["name"]
          if elements.has_key(value["name"]):
            elements[value["name"]] += int(initial_score)
          elements[value["country"]] = initial_score

      # using the user hash in the tweet stream
      elif key == 'user':
        print "value"
Example #16
0
    def test_reverse_geocode(self):
        """
        Test pygeocoder reverse_geocode()

        """
        lat, lng = 38.897096, -77.036545
        result = Geocoder.reverse_geocode(lat, lng)

        self.assertEqual(result.country__short_name, 'US')
        self.assertEqual(result.postal_code, '20500')
        self.assertEqual(result.street_number, '1600')
        self.assertEqual(result.route, 'Pennsylvania Avenue Northwest')
        self.assertEqual(result.administrative_area_level_1,
                         'District of Columbia')
        self.assertEqual(result.city, 'Washington')
        self.assertEqual(result.state, 'District of Columbia')
        self.assertEqual(result.state__short_name, 'DC')
        self.assertEqual(result.country, 'United States')
        addr = result.formatted_address
        self.assertEqual(
            addr,
            "1600 Pennsylvania Avenue Northwest, President's Park, Washington, DC 20500, USA"
        )
        lat2, lng2 = result.coordinates
        self.assertAlmostEqual(lat, lat2, 3)
        self.assertAlmostEqual(lng, lng2, 3)
        self.assertAlmostEqual(lat, result.latitude, 3)
        self.assertAlmostEqual(lng, result.longitude, 3)
        self.assertTrue(result.count > 1)
Example #17
0
def get_geolocation_by_latlong(latitude, longitude):
    # call google geolocation service to get the location detail
    results = Geocoder.reverse_geocode(latitude, longitude)
    if results is not None and len(results) > 0:
        google_location = results.raw[0]

        location = Geolocation()
        location.latitude = google_location['geometry']['location']['lat']
        location.longitude = google_location['geometry']['location']['lng']

        address_components = google_location['address_components']
        for component in address_components:
            if 'street_number' in component['types']:
                location.street_num = component['long_name']
            if 'route' in component['types']:
                location.street_name = component['long_name']
            if 'neighborhood' in component['types']:
                location.lv1_district = component['long_name']
            if 'locality' in component['types']:
                location.city = component['long_name']
            if 'administrative_area_level_1' in component['types']:
                location.state = component['long_name']
            if 'country' in component['types']:
                location.country = component['long_name']
            if 'postal_code' in component['types']:
                location.zipcode = component['long_name']
        return location
    else:
        return None
Example #18
0
def fetch_geo_details(garden):
    """Reverse geocode to get garden's state, city, etc"""
    results = Geocoder.reverse_geocode(garden.latitude, garden.longitude)
    address_components = results[0].data[0]['address_components']

    for component in address_components:
        # Borough
        if 'sublocality' in component['types']:
            borough = component['long_name']
            if not garden.borough and borough in [
                    b[0] for b in Garden.BOROUGH_CHOICES
            ]:
                garden.borough = component['long_name']

        # City
        if 'locality' in component['types']:
            if not garden.city:
                garden.city = component['long_name']

        # State
        if 'administrative_area_level_1' in component['types']:
            if not garden.state:
                garden.state = component['short_name']

        # Zip
        if 'postal_code' in component['types']:
            if not garden.zip:
                garden.zip = component['long_name']

    garden.save()
Example #19
0
def generate_map_and_desc(gps_data,mode,marker_list):
    ischina=False
    api_key='AIzaSyBepV-5hoVd8xzwkdE93I0eRKf2jTlys3U'
    gmaps = GoogleMaps(api_key)
    gps=gps_data
    try:
        result = Geocoder.reverse_geocode(gps_data[0],gps_data[1])
        destination = str(result)
    except:
        destination = 'N/A'
    
    if mode==0:
        dmap=DecoratedMap(size_x=400,size_y=400)
    else:
        dmap=DecoratedMap(size_x=400,size_y=400, maptype='satellite')

    dmap.add_marker(LatLonMarker(lat=gps[0],lon=gps[1],label='A'))
    for i in range(0, len(marker_list)):
        dmap.add_marker(LatLonMarker(lat=marker_list[i][0],lon=marker_list[i][1],label=chr(66+i)))

    cmap = CenterMap(lat=gps[0],lon=gps[1], zoom=12)
    map_url=dmap.generate_url()
    print(map_url)
    f=open('tmp.png','wr')
    f.write(urllib.urlopen(map_url).read())
    f.close()

    return destination
Example #20
0
def fetch_geo_details(garden):
    """Reverse geocode to get garden's state, city, etc"""
    results = Geocoder.reverse_geocode(garden.latitude, garden.longitude)
    address_components = results[0].data[0]['address_components']

    for component in address_components:
        # Borough
        if 'sublocality' in component['types']:
            borough = component['long_name']
            if not garden.borough and borough in [b[0] for b in Garden.BOROUGH_CHOICES]:
                garden.borough = component['long_name']

        # City
        if 'locality' in component['types']:
            if not garden.city:
                garden.city = component['long_name']

        # State
        if 'administrative_area_level_1' in component['types']:
            if not garden.state:
                garden.state = component['short_name']

        # Zip
        if 'postal_code' in component['types']:
            if not garden.zip:
                garden.zip = component['long_name']

    garden.save()
Example #21
0
def GeoCoordinates(URL):
    z = 0
    Country_Dictionary = pickle.load(open("Countries_.p", "rb"))
    while z < 10:
        z += 1
        time.sleep(2)
        coordinates = []
        acoordinates = []
        chrome_path = r"C:\Users\Ericlameguy\Desktop\chromedriver_win32 (1)\chromedriver.exe"
        options = Options()
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        driver = webdriver.Chrome(chrome_path, chrome_options=options)
        driver.get(URL)
        html = driver.execute_script("return document.documentElement.innerHTML;")

        newhtml = html.split("https://maps.google.com/maps/@",1)[1]
        coordinates.append(float(newhtml.split(',')[0]))
        coordinates.append(float(newhtml.split(',')[1]))

        acoordinates.append(coordinates)
        result = Geocoder.reverse_geocode(*acoordinates[0])

        Country = result.country

        driver.quit()
        if Country not in Country_Dictionary:
            Country_Dictionary[Country] = 1
        elif Country in Country_Dictionary:
            Country_Dictionary[Country] += 1

    for key, value in sorted(Country_Dictionary.items(), key=operator.itemgetter(0)):
        print(key, value)

    pickle.dump(Country_Dictionary, open("Countries_.p","wb"))
def detectCountry(lat,lng):
    #url_geo = "http://ws.geonames.org/countryCode?lat=%s&lng=%s" %(lat,lng)
    print "Detecting: ",lat,lng
    results = Geocoder.reverse_geocode(lat, lng)
    if "Brazil" == results:
        results = "Brasil"
    return results[0].country
def getState(coords_list):
	lat = coords_list[0]
	log = coords_list[1]
	address = Geocoder.reverse_geocode(lat, log)
	state = address.state.encode('ascii', 'ignore')
	if state in states.states.items():
		return state
	return None
Example #24
0
def get_location_by_latlng(lat, lng):
    try:
        result = Geocoder.reverse_geocode(float(lat), float(lng))
        locations = map(lambda x: x.replace(" ", ""),
                        result.formatted_address.split(","))
        return locations[::-1]
    except:
        return None
Example #25
0
def pointToAddr(latitude,longitude):
    try:
        results=Geocoder.reverse_geocode(longitude,latitude) #geocoder quirk
        address=results[0].formatted_address
    except GeocoderError as e:
        error(e)
        
    return address
def tweet():
  args = get_args()
  creds = load_credentials()
  
  shortener = Shortener('Google', api_key=creds[0])
  tweet = Twitter(auth=OAuth(creds[1], creds[2], creds[3], creds[4]))
        
  url = "http://127.0.0.1:" + str(args.port) + "/raw_data"
  response = urllib.urlopen(url)
  dump = json.loads(response.read())
  new = copy.deepcopy(dump)
  old = {
    'pokemons': []
  }
  
  if os.path.isfile('data.json'):
    with open('data.json') as data_file:
      old = json.load(data_file)

  # Deletes encounter id for next step
  for e_new in new['pokemons']:
    for e_old in old['pokemons']:
      if e_new['encounter_id'] == e_old['encounter_id']:
        del e_new['encounter_id']
        break

  # Existing encounter ids are rare pokemon
  # This entire step is to parse the data for a tweet
  for e_new in new['pokemons']:
    if e_new['pokemon_id'] in rares:
      if 'encounter_id' in e_new:
        location = str(Geocoder.reverse_geocode(e_new['latitude'], e_new['longitude'])[0]).split(',')
        destination = location[0]
        if len(location) == 5:
          destination += ", " + location[1]
        time = datetime.datetime.fromtimestamp(e_new['disappear_time']/1000)
        ampm = "AM"
        hour = time.hour
        gmap = 'https://www.google.com/maps/dir/Current+Location/' \
                + str(e_new['latitude']) + ',' + str(e_new['longitude'])
        if hour > 12:
          hour -= 12
          ampm = "PM"
        elif hour == 12:
          ampm = "PM"
        elif hour == 0:
          hour = 12
        tweeting = "{} at {} until {}:{}:{} {}. #PokemonGo {}".format( \
          e_new['pokemon_name'], destination, \
          hour, str(time.minute).zfill(2), str(time.second).zfill(2), ampm, \
          shortener.short(gmap))
        tweet.statuses.update(status=tweeting)
        print tweeting
        # Google api timeout
        t.sleep(0.5)
    
  with open('data.json', 'w') as outfile:
    json.dump(dump, outfile)
Example #27
0
def get_loc_geocoder(lats, longs):
    retloc = []
    for i in range(len(lats)):
        try:
            g = Geocoder.reverse_geocode(lats[i], longs[i])
            retloc.append(g.country)
        except:
            retloc.append('N/A')
    return retloc
Example #28
0
def get_zipcode_by_latlong(latitude, longitude):
    results = Geocoder.reverse_geocode(latitude, longitude)
    if results is not None and len(results) > 0:
        google_location = results.raw[0]
        address_components = google_location['address_components']
        for component in address_components:
            if 'postal_code' in component['types']:
                return component['long_name']
    return None
def impute_zip(df):
    geocoder = Geocoder('your-api-key')
    tqdm_notebook().pandas()
    df.loc[df["zipcode"].isnull(),
           "zipcode"] = df[df["zipcode"].isnull()].progress_apply(
               lambda row: geocoder.reverse_geocode(row['latitude'], row[
                   'longitude'])[0].postal_code,
               axis=1)
    return (df)
def loc2address(kdeCenterGeo,flagRandom=0):
    address=[]
    if(flagRandom>0):
        address.append("Park at your own risk, crimes appear to be randomly distributed in this area.")
    else:
        for i in range(kdeCenterGeo.shape[0]):
            add=str(Geocoder.reverse_geocode(kdeCenterGeo[i,1],kdeCenterGeo[i,0]))
            address.append(add[:-15])
    return address
Example #31
0
def getRandomPlace():
    while True:  # try for coordinates (departure) that correspond to a valid address
        try:
            location = getCoordinates()  # get random coordinates
            address = Geocoder.reverse_geocode(location[0], location[1])
            break
        except:
            pass
    return (location, address)
Example #32
0
 def get_address_string(self):
     if self.address:
         result = Geocoder.reverse_geocode(
             self.address.latitude,
             self.address.longitude,
             language='ru'
         )
         return str(result)
     return None
Example #33
0
def get_loc_geocoder(lats, longs):
    retloc = []
    for i in range(len(lats)):
        try:
            g = Geocoder.reverse_geocode(lats[i], longs[i])
            retloc.append(g.country)
        except:
            retloc.append('N/A')
    return retloc
Example #34
0
    def findLoc(self, lat, lon):
        self.lat = lat
        self.lon = lon

        self.results = Geocoder.reverse_geocode(self.lat, self.lon)

        print(self.results)

        return self.results
def latlong_to_zipcode(lat, lon):
    """
    Takes in zipcode and returns the corresponding latitude and longitude
    :param lat: Latitude
    :param lon: Longitude
    :return: zipcode
    """
    results = Geocoder.reverse_geocode(lat, lon)
    return results[0].postal_code
Example #36
0
def Fetch():
	response = urllib.urlopen(url)
        data = json.loads(response.read())
        lat = data['latitude']
        lon = data['longitude']       
	try:
		addr =  Geocoder.reverse_geocode(lat, lon)
		return lat, lon, addr
	except:
		return 0,0
def get_county_name(longitude, latitude, placeID = None):
    url_prefix = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='
    #placeID and longitude and latitude
    key = 'AIzaSyAw-2MPkd3FbwnTjNpsaai1tsIzUk-B2aA'
    geocoder_obj = Geocoder(None, key)
    print "Lookup of Address Begin"
    results = geocoder_obj.reverse_geocode(longitude, latitude)
    print type(results)
    address = results.split()
    print address
Example #38
0
def get_userZipcode(user):
    location = detect_home_from_db(user)
    if location != 'N/A':
        # Convert from our internal GeoJSON specific (lng, lat) to the (lat, lng)
        # format required by geocoder
        zipcode = Geocoder.reverse_geocode(location[1], location[0])
        zip = zipcode[0].postal_code
        return zip
    else:
        return 'N/A'
Example #39
0
def loc():
	a = run_command(adb_commands['get-location'])
	a = a.split("Location[network")[1].split("acc")[0]
	latitude = a.split(",")[0]
	longitude = a.split(",")[1]
	#print "latitude:", latitude
	#print "longitude:", longitude

	results = Geocoder.reverse_geocode(float(latitude),float(longitude))
	return str(results).split(',')[0].decode('unicode_escape').encode('ascii','ignore')
Example #40
0
def reverse_geocode(latitude, longitude):
    
    '''Perform reverse geocoding to identify each tweet's US state, if any'''    

    # Perform reverse geocoding
    try:
        geo_obj = Geocoder.reverse_geocode(latitude, longitude)
    except Exception, e:
        print stderr, 'Encountered exception:', e
        return None
Example #41
0
def get_location(tweet):
	if tweet['coordinates']:
		lat,lon = tuple(tweet['coordinates']['coordinates'])
		try:
			location = Geocoder.reverse_geocode(lat,lon)
			if location.state == 'United States':
				return us.states.lookup(location.administrative_area_level_1).abbr.strip()
		except:
			pass
	elif tweet['place']:
		return tweet['place']['full_name'].split(',')[-1].strip()
Example #42
0
def _geocodeZipcode(user_pro, location):
    try:
        zipcode = Geocoder.reverse_geocode(location[1],location[0])
        zipc=zipcode[0].postal_code
        # user_pro['zip'] = zip
    except:
        zipc = 'N/A'
    if zipc == None:
        zipc = 'N/A'
    user_pro['zip'] = zipc
    return zipc
Example #43
0
def reverse( lat, long):
    
    from pygeocoder import Geocoder
    results = Geocoder.reverse_geocode( lat, long)
    print(results)
    print(results.country)
    print(results.continent)
    print(results.zip_code)
    print(results.state)
    print(results.city)
    return results
Example #44
0
def main():

    exCoords = [59.925639, 10.722448]

    url = "http://animalia-life.com/data_images/bird/bird1.jpg"
    geoData = Geocoder.reverse_geocode(exCoords[0], exCoords[1])
    message = "TEST: Pothole encountered at (" + str(exCoords[0]) + "," + str(
        exCoords[1]) + ") in " + str(geoData.street_name) + ", " + str(
            geoData.city)
    print(message)
    tweet_image(url, message)
Example #45
0
 def printCoordinates(self, coordiantes):
     print "Coordinate Lookup: (" + str(len(coordiantes)) + ")"
     dispLen = len(str(coordiantes[max(coordiantes, key = lambda x: coordiantes.get(x) )]['cnt']))
     for key in coordiantes:
         print "[%*d] (%.3f, %.3f) -->" % (dispLen, coordiantes[key]['cnt'], key[0], key[1]),
         successfulLookup = False
         lookupCount      = 0
         while (not successfulLookup) and (lookupCount < 5):
             try:
                 print Geocoder.reverse_geocode(key[0], key[1])
                 successfulLookup = True
             except Exception, e:
                 # print e
                 if "ZERO_RESULTS" in e:
                     lookupCnt = float('Inf')
                     break
                 time.sleep(.5)
                 lookupCount += 1
         if (not successfulLookup) or (lookupCount > 5):
             print "No results found..."
Example #46
0
def mapLocation(lat,lon):
	results = Geocoder.reverse_geocode(float(lat),float(lon))
	#results = Geocoder.reverse_geocode(30.97548,76.53786)#iit ropar
	#results = Geocoder.reverse_geocode(30.76239,76.78031)#women's hostel
	#results = Geocoder.reverse_geocode(23.76239,76.98031)
	#print results[0]

	#print results[1]
	#print results[2]
	#print results
	return results
Example #47
0
    def hydrate(self, bundle, request=None):
        if not bundle.obj.pk:
            bundle.data['created_by'] = bundle.request.user

        # Resolve position
        position = bundle.data['position']['coordinates']
        geo_results = Geocoder.reverse_geocode(position[0], position[1])
        if len(geo_results) > 0:
            bundle.data['address'] = geo_results[0]
            
        return bundle
Example #48
0
def get_city():
	a = run_command(adb_commands['get-location'])
	a = a.split("Location[network")[1].split("acc")[0]
	latitude = a.split(",")[0]
	longitude = a.split(",")[1]
	#print "latitude:", latitude
	#print "longitude:", longitude

	results = Geocoder.reverse_geocode(float(latitude),float(longitude))
	c = results.city
	return c
Example #49
0
def try_reverse_geocode_until_success(latitude, longitude):
    success = False
    attempts = 2
    results = []
    geocoder = Geocoder()
    while not success and attempts < 3:
        try:
            results = geocoder.reverse_geocode(latitude, longitude)
            success = True
        except:
            attempts += 1
            sleep(2)
    return results, success
Example #50
0
def reverse_geocode(lat, lon):
    results = Geocoder.reverse_geocode(lat, lon)

    data = {
        'postal_code': results.postal_code,
        'city': results.city,
        'state': results.state,
        'county': results.county,
        'country': results.country,
        'address': str(results),
    }

    return data
Example #51
0
    def get_address_by_location(location: object):

        try:
            location = str(
                Geocoder.reverse_geocode(
                    location.NEBoundLatitude,
                    location.NEBoundLongitude)).split(",")[0]
        except GeocoderError as e:
            raise Exception(
                4 * "<" + "[ERROR]" + 4 * ">" +
                "An error occurred when trying to create a location." +
                "\nERROR: " + format(e) + "\n")
        return location
Example #52
0
 def test(self):
     workDetection = pygmaps.maps(37.8656475757, -122.258774009,14)
     for user in get_section_db().distinct('user_id'):
         user_work=work_place.detect_work_office(user)
         print user
         if user_work == 'N/A' or '':
             print '--- USER WORK ADDRESS UNAVAILABLE ---'
         else:
             print(Geocoder.reverse_geocode(user_work[0], user_work[1])[0])
             workDetection.addpoint(user_work[0], user_work[1], "#FF0000")
         print '...'
     if not os.path.exists('gmap_display'):
         os.makedirs('gmap_display')
     workDetection.draw('gmap_display/workDetection.html')
Example #53
0
 def test(self):
     homeDetection = pygmaps.maps(37.8656475757, -122.258774009,14)
     for user in get_section_db().distinct('user_id'):
         user_home=home.detect_home(user)
         print user
         if user_home == 'N/A' or '':
             print '--- USER HOME ADDRESS UNAVAILABLE ---'
         else:
             print(Geocoder.reverse_geocode(user_home[0], user_home[1])[0])
             homeDetection.addpoint(user_home[0], user_home[1], "#FF0000")
         print '...'
     if not os.path.exists('gmap_display'):
         os.makedirs('gmap_display')
     homeDetection.draw('gmap_display/homeDetection.html')
Example #54
0
 def add_to_database(self, input):
     con = self.connect_to_database()
     cur = con.cursor()
     USERID = input[0]
     CONTENT = input[1]
     GPS = input[2] + ',' + input[3]
     LOCATION = str(
         Geocoder.reverse_geocode(float(input[2]), float(input[3]))[0])
     TIME = str(datetime.datetime.utcnow())
     with con:
         cur.execute(
             "INSERT INTO BLASTS(USERID,CONTENT,GPS,LOCATION,TIME) VALUES(\'%s\', \'%s\', \'%s\', \'%s\', \'%s\');"
             % (USERID, CONTENT, GPS, LOCATION, TIME))
     con.close()
Example #55
0
def LatLonToZip(lat, lon):
    """Returns Zip code for Lat/Lon (Using Google Maps Reverse Geocoding API)
       Usage Limit:
       https://developers.google.com/maps/documentation/geocoding/#Limits
    """
    try:
        results = Geocoder.reverse_geocode(lat, lon)
        return results[0].postal_code
    except Exception as e:
        print e.status
        if e.status != GeocoderError.G_GEO_ZERO_RESULTS:
            # Raise except if OVER_USAGE_LIMIT
            raise
        return None
Example #56
0
    def get(self):
        self.get_current_user()
        kwargs = dict(self.application.static_kwargs)
        kind = self.get_argument('kind')
        kwargs['page_name'] = kind
        kwargs['config'] = config
        query = self.get_argument('query', None)
        radius = self.get_argument('radius', None)
        if query is None or query == '':
            lat = self.get_argument('lat', None)
            lng = self.get_argument('lng', None)
            if lat is None or lng is None:
                lat = '40.050137'
                lng = '-74.221251'
            if radius is None:
                radius = '100'
        else:
            query = self.get_argument('query', None)
            google = GoogleGeo(self.db, config)
            query_results = google.address_search(query)
            query_array = query_results['response']

            ## get 1st result
            lat = query_array[0]['geometry']['location']['lat']
            lng = query_array[0]['geometry']['location']['lng']
            if radius is None:
                radius = '100'

        geo_results = Geocoder.reverse_geocode(float(lat), float(lng))
        kwargs['full_address'] = geo_results[0]

        resource = Resource(self.db, config)
        results = resource.list(kind, lat, lng, radius)
        kwargs['resource_objects'] = results['response']
        if int(len(results['response'])) == 0:
            self.write(
                self.application.loader.load(
                    'mobile/resources_none.html').generate(**kwargs))
            return

        if kind == 'employment':
            jobs = resource.list('job', lat, lng, radius)
            kwargs['jobs'] = jobs['response']

            job_gig = resource.list('job_gig', lat, lng, radius)
            kwargs['job_gig'] = job_gig['response']

        self.write(
            self.application.loader.load('mobile/resources.html').generate(
                **kwargs))