예제 #1
0
파일: test4_NYC.py 프로젝트: gilk/cityplan
def distances(start_address,end_address):
	gmaps = GoogleMaps()
	
	base_url = 'http://maps.googleapis.com/maps/api/directions/json?'
	
	travel_mode='mode=walking'
	
	if start_address==end_address:
		return False
	
	start_lat, start_longt = gmaps.address_to_latlng(start_address+', New York, USA')	#Getting the longtitudes and lattitudes of given addresses
	end_lat, end_longt = gmaps.address_to_latlng(end_address+', New York, USA')
	sensor='sensor=false'
	
	test_url=base_url+'&'+travel_mode+'&'+'origin='+str(start_lat)+','+str(start_longt)+'&destination='+str(end_lat)+','+str(end_longt)+'&'+sensor	#Constructs the url to query google maps for walking directions
	print test_url
	
	result = json.load(urllib.urlopen(test_url)) 
	
	met_distance = result['routes'][0]['legs'][0]['distance']['value']	#obtain the walking distance in km
	print 'Metropolitan distance between ', start_address, 'and', end_address , ' is ',met_distance, 'm'
	
	#calculate the straight line distance (over the surface of the Earth) assuming the Earth is a sphere of radius 6378100m
	dlat = m.radians(end_lat-start_lat)
	dlongt = m.radians(end_longt-start_longt)
	
	a = ((m.sin(dlat/2))*(m.sin(dlat/2)))+(m.cos(m.radians(start_lat)) * m.cos(m.radians(end_lat)) * (m.sin(dlongt/2))*(m.sin(dlongt/2)) )
	c = 2 * m.atan2(m.sqrt(a), m.sqrt(1-a))
	d = 6378100 * c
	print 'Whereas line of flight distance is' , d,'m'
	if d == 0 : return False
	rat = met_distance/d
	if rat < 1 : rat = 1
	return rat
예제 #2
0
파일: workspace.py 프로젝트: pshirkey/dodah
 def post(self):
     
     models.Difficulty.load()
     
     models.User.get_test_user()
     self.redirect(Index.url)
     
     cat = models.Category(name="Food/Beverage", description="")
     cat.put()
     
     subcat = models.Category(name="Resturant", description="", parent_category=cat)
     subcat.put()
     
     subcat = models.Category(name="Coffee House", description="", parent_category=cat)
     subcat.put()
     
     red = models.Location(owner=self.current_user, location=db.GeoPt(37, -122))
     red.address = "310 SW 3rd Street"
     red.name = "Red Horse"
     red.description = "Red Horse Coffee"
     red.category = subcat
     red.city = "Corvallis"
     red.state = "OR"
     red.zip = "97333"
     red.county = "USER"
     red.phone_number = "(541) 757-3025"
     red.rating = 99
     red.put()
     gmaps = GoogleMaps(self.enviroment.google_maps_key)   
     lat, lng = gmaps.address_to_latlng(red.get_address())
     red.update_location(db.GeoPt(lat, lng))
     red.save()
예제 #3
0
파일: views.py 프로젝트: saahil/U_Need
def lookup(request):
	what = (request.POST['what']).lower()
	where = (request.POST['where']).lower()

	api = twython.setup('Basic', username='******', password='')
	gmaps = GoogleMaps()

	mentions = api.getUserMentions(since_id=4698625520)

	a = []

	lat1, lng1 = gmaps.address_to_latlng(where)

	#if is not (api):
	#	render_to_response('need/enter.html')

	for stat in mentions:
		text = (stat["text"]).lower()
		ele = text.split(':')
		lat2 = float(ele[2])
		lng2 = float(ele[3])
		if (text.find(what) != -1) and (in_vic(lat1, lng1, lat2, lng2) == 1):
			actual = gmaps.latlng_to_address(lat2, lng2)
			tweet = ele[1] + " " + actual
			a.append(tweet)

	t = loader.get_template("need/results.html")

	c = Context({'stat': a},)
	return HttpResponse(t.render(c))
예제 #4
0
def get_location(zipcode):
    
    gmaps = GoogleMaps(API_key)

    latlong = gmaps.address_to_latlng(zipcode)

    return latlong
예제 #5
0
파일: scrape.py 프로젝트: lesion/strumenti
  def add_case( self, case ):
    from googlemaps import GoogleMaps
    from time import sleep

    gmaps = GoogleMaps()

    for casa in case:
      casa['cap'] = int( casa['cap'] )
      sleep( 0.2 ) 
      print "Calcolo latitudine/longitudine"

      ( casa['latitudine'], 
        casa['longitudine'] ) = gmaps.address_to_latlng( "%s %d, %s, %s" % ( 
                                                          casa['indirizzo'], casa['cap'], 
                                                          casa['comune'], casa['provincia'] ) ) 
                                                      

      casa['allegati'] = casa['allegati'].replace(' ',',')

      casa['tipo'] = casa['vendita'].upper()
      del( casa['vendita'] )

      casa['base'] = int( casa['costo'].replace('.','').split(',')[0] )
      del( casa['costo'] )

      self.conn.insert( 'case', casa )
      print
예제 #6
0
파일: service.py 프로젝트: pshirkey/dodah
 def do_post(self):
     address = self.param('address')
     lat = self.param('lat')
     lon = self.param('lon')
     miles = self.request.get('miles', default_value=10)
     max_results = self.request.get('max_results', default_value=10)
     geoPoint = None
     try:
         if address:
             try:
                 gmaps = GoogleMaps(self.enviroment.google_maps_key)   
                 lat, lon = gmaps.address_to_latlng(address)
             except:
                 self.write_error('Cannot get position from address')
                 return
         geoPoint = db.GeoPt(lat, lon)
     except:
         self.write_error('Error validating position')
         return
     
     if geoPoint:
         meters = float(miles) * base.METERS_IN_MILE        
         locations = models.Location.proximity_fetch( models.Location.all(), geoPoint, int(max_results), meters )
         if locations and len(locations) > 0:
             json = []
             for loc in locations:             
                 json.append(loc.to_json_object())
             self.write_success(json)
         else:
             self.write_error("No Locations within %s miles" % miles)
예제 #7
0
파일: models.py 프로젝트: cjmcfaul/italian
 def get_lat_long(self):
     from googlemaps import GoogleMaps
     gmaps = GoogleMaps(italian - 1489414695369)
     Address = self.address
     lat, lng = gmaps.address_to_latlng(address)
     self.latitude = lat
     self.longitude = lng
     save()
예제 #8
0
 def _geo_loc(self, cr, uid, ids, field_name, arg, context):
     result = {}
     gmaps = GoogleMaps("http://maps.googleapis.com/maps/api/js?key=AIzaSyBwNE-vFDyyOb62ODaRiqpiL2kz8wR0aTc")
     for partner in self.browse(cr,uid,ids):
         address = partner.street
         lat, lng = gmaps.address_to_latlng(address) 
         latlng = str(lat) +","+ str(lng)
         result[partner.id] = str(latlng)
     return result
예제 #9
0
파일: GMaps.py 프로젝트: KFishner/tivly2012
def getMap(businessid):
    GOOGLEMAPS_API_KEY = settings.GOOGLEMAPS_API_KEY
    gmaps = GoogleMaps(GOOGLEMAPS_API_KEY)
    business = Businesses.objects.filter(businessID = businessid)[0]
    address = business.street + ' ' + business.city + ' ' + str(business.zipCode)
    lat, lng = gmaps.address_to_latlng(address)
    return lat,lng
        
        
예제 #10
0
def returnCoordinate(tweets):
    gmaps = GoogleMaps('AIzaSyB8YS_1RgpdLZogrpNsZ6V7Yc6mKJAE_og')
    updated=[]
    for tweet in tweets:
        location=re.search('where:([\w]+)', lower(tweet['text']))
        if location:
            address = location.group(1)
            lat, lng = gmaps.address_to_latlng(address)
            updated.append([location, lat, lng])
    return updated
예제 #11
0
    def test_point_from_latlng(self):
        gmaps = GoogleMaps(settings.GOOGLEMAPS_API_KEY)
        latlng = gmaps.address_to_latlng(u'Jose javier Diaz 440, cordoba, argentina', )
        point=None
        try:
            point =  MaapPoint(geom=Point(latlng).wkt)
            point.save()            
        except Exception, e:

            self.assertIsNotNone(point, msg=e)
예제 #12
0
 def createMap(self):  
     gmaps = GoogleMaps("ABQIAAAAQQRAsOk3uqvy3Hwwo4CclBTrVPfEE8Ms0qPwyRfPn-DOTlpaLBTvTHRCdf2V6KbzW7PZFYLT8wFD0A")
     address = self.location
     lat, lng = gmaps.address_to_latlng(address)
     m = pymaps.PyMap(lat, lng)
     m.key = "ABQIAAAAQQRAsOk3uqvy3Hwwo4CclBTrVPfEE8Ms0qPwyRfPn-DOTlpaLBTvTHRCdf2V6KbzW7PZFYLT8wFD0A"
     m.maps[0].zoom = 17
     q = [lat,lng, 'Search Result Location: '+ address] 
     m.maps[0].setpoint(q)
     open('test.html','wb').write(m.showhtml())   # generate test file
     webbrowser.open('test.html')
예제 #13
0
def get_loc(address):

	api_key = "ABQIAAAA_Nl9CTT83Tx0_6m45f7SQxRfRo7TXTpgZcKZw6sB7U7ZlfQK2BQV36qlGpf3-HF0Ntlqdf8T-Gaqxg"

	gmaps = GoogleMaps(api_key)

	lat, lng = gmaps.address_to_latlng(address)

	print lat, lng

	return lat, lng
예제 #14
0
 def _geo_loc(self, cr, uid, ids, field_name, arg, context):
     result = {}
     gmaps = GoogleMaps(
         "http://maps.googleapis.com/maps/api/js?key=AIzaSyBwNE-vFDyyOb62ODaRiqpiL2kz8wR0aTc"
     )
     for partner in self.browse(cr, uid, ids):
         address = partner.street
         lat, lng = gmaps.address_to_latlng(address)
         latlng = str(lat) + "," + str(lng)
         result[partner.id] = str(latlng)
     return result
예제 #15
0
def FindPizza():
	print "Enter in an address to find Pizza places near it"
	address = raw_input()
	gmaps = GoogleMaps("AIzaSyA5R4PnzAcoe2vpVRKyWWby-d6RrMmIwtQ")
	lat, lng = gmaps.address_to_latlng(address)
	destination = gmaps.latlng_to_address(lat, lng)
	Pizza = gmaps.local_search('pizza near ' + destination)
	directions = gmaps.directions(address, destination)
	print "The nearest Pizza place is " + Pizza['responseData']['results'][0]['titleNoFormatting']
	for step in directions['Directions']['Routes'][0]['Steps']:
		print step['descriptionHtml']
예제 #16
0
파일: views.py 프로젝트: wolvelopez/mitapa2
def lugarnuevo(request):
    if request.method == 'POST':
        formulario = LugarNuevo(request.POST)
        if formulario.is_valid():
            #Obtencion de valores del formulario para generar el XML
            direccion = formulario.cleaned_data['direccion']
            print direccion
            poblacion = formulario.cleaned_data['poblacion']
            print poblacion
            nombre = formulario.cleaned_data['nombre']
            print nombre
            tipo = formulario.cleaned_data['tipo']
            print tipo
            gmaps = GoogleMaps('AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A')
            direccion = direccion + ',' + poblacion
            lat, lng = gmaps.address_to_latlng(direccion)
            lat = str(lat)
            lng = str(lng)
            if tipo == '1':
                tipo = 'bar'
            elif tipo == '2':
                tipo = 'cafeteria'
            elif tipo == '3':
                tipo = 'comida'
            elif tipo == '4':
                tipo = 'restaurante'
            print tipo
            xml = "<PlaceAddRequest>" + "<location>" + "<lat>" + \
                lat + \
                "</lat>" + "<lng>" + lng + "</lng>" + \
                "</location>" + \
                "<accuracy>" + "5" + "</accuracy>" + \
                "<name>" + nombre + "</name>" + \
                "<type>" + tipo + "</type>" + \
                "<language>" + "es" + "</language>" + \
                "</PlaceAddRequest>"
            #print xml
            ##utilizamos request, una libreria mas optimizada que urllib2
            #r = requests.post('https://maps.googleapis.com/maps/api/place/ \
            #add/xml?sensor=false&key= \
            #AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A', xml)
            #print r.content
            url = 'https://maps.googleapis.com/maps/api/place/add/xml?sensor=false&key=AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A'
            req = urllib2.Request(url,
                xml,
                headers={'Content-Type': 'application/xml'})
            consulta = urllib2.urlopen(req)
            print consulta.read()
    else:
        formulario = LugarNuevo()
    return render_to_response('lugarnuevo.html', {'formulario': formulario},
    context_instance=RequestContext(request))
예제 #17
0
def select(paras):
    gmaps = GoogleMaps()
    address = paras['street'] + ", " + paras['city'] + ", " + paras['state']
    latitude, longtitude = gmaps.address_to_latlng(address)
    print "Location convertion: " + str(latitude) + str(longtitude)
    time_start_mon = int(paras['s_mon'])
    time_start_day = int(paras['s_day'])
    time_start_hour = int(paras['s_hou'])
    time_end_mon = int(paras['e_mon'])
    time_end_day = int(paras['e_day'])
    time_end_hour = int(paras['e_hou'])
    radius = paras['r']
    start_time = datetime.datetime(2012, time_start_mon, time_start_day,
                                   time_start_hour, 0)
    end_time = datetime.datetime(2012, time_end_mon, time_end_day,
                                 time_end_hour, 0)
    start_epoch_time = time.mktime(start_time.timetuple()) * 1000
    end_epoch_time = time.mktime(end_time.timetuple()) * 1000
    distance = "3959*acos((sin({3}/57.29577951)*sin(latitude/57.29577951)+cos({3}/57.29577951)*cos(latitude/57.29577951)*cos(abs(longtitude-({2}))/57.29577951))) <{4}"
    querystr = (
        "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} and "
        + distance + " order by user;").format(start_epoch_time,
                                               end_epoch_time, longtitude,
                                               latitude, radius)

    if (paras['r'] == '0'):
        querystr = (
            "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} order by user;"
        ).format(start_epoch_time, end_epoch_time)
    print querystr
    con, cur = sql_execute(querystr)

    data = []
    while True:
        dat = cur.fetchone()
        if dat == None:
            break
        data.append(dat)
    if (paras['type'] == '0'):
        return top_k_similar(data, paras['option1'], paras['option2'],
                             paras['deadline'])
    if (paras['type'] == '1'):
        return mst.call_mst(data, paras['deadline'])
    if (paras['type'] == '2'):
        return kmeans_new.call_kmeans(data, paras['deadline'],
                                      int(paras['option1']))
    if (paras['type'] == '3'):
        return represent.call_represent(data, paras['deadline'],
                                        int(paras['option1']))
    else:
        return [], []
    pass
예제 #18
0
파일: views.py 프로젝트: saahil/U_Need
def tweet(request):
	api = twython.setup('Basic', request.session['username'], request.session['password'])
	gmaps = GoogleMaps()

	what = request.POST['what']
	where = request.POST['where']

	lat, lng = gmaps.address_to_latlng(where)
	tweet = "@U_Need :" + what + ":" + str(lat) + ':' + str(lng) + ":#ihave"

	api.updateStatus(tweet)

	return render_to_response('have/add.html')
예제 #19
0
 def test_location(self):
     if not hasattr(self, "_test_location"):
         self._test_location = None
         if models.Category.all().count() <= 0:
             cat = models.Category(name="Food/Beverage", description="")
             cat.put()
             
             subcat = models.Category(name="Resturant", description="", parent_category=cat)
             subcat.put()
             
             subcat = models.Category(name="Coffee House", description="", parent_category=cat)
             subcat.put()
         
         self._test_location = models.Location.gql("WHERE name='Some Coffee Place'").get()
         if not self._test_location:        
             models.Difficulty.load()    
             self._test_location = models.Location(owner=models.User.get_test_user(), location=db.GeoPt(37, -122))
             self._test_location.address = "310 SW 3rd Street"
             self._test_location.name = "Some Coffee Place"
             self._test_location.description = "Some Coffee Place used for testing"
             self._test_location.category = models.Category.gql("WHERE name='Coffee House'").get()
             self._test_location.city = "Corvallis"
             self._test_location.state = "OR"
             self._test_location.zip = "97333"
             self._test_location.county = "USA"
             self._test_location.phone_number = "(541) 757-3025"
             self._test_location.rating = 48
             self._test_location.put()
             gmaps = GoogleMaps(self.enviroment.google_maps_key)   
             lat, lng = gmaps.address_to_latlng(self._test_location.get_address())
             self._test_location.update_location(db.GeoPt(lat, lng))
             self._test_location.save()
             
             difficulty = models.Difficulty.find( 'MEDIUM' )
             oneMonth = datetime.timedelta(days=30)
             today = datetime.date.today()
             expires = today + oneMonth
         
             for i in range(1, 5):
                 code = self._create_item_code()
                 item = models.Item.get_by_key_name(code)
                 while item:
                     code = self._create_item_code()
                     item = models.Item.get_by_key_name(code)
                 item = models.Item(key_name=code, location=self._test_location,
                                    name="Free 20oz Coffee", 
                                    details="Show Code at Counter to get a Free Coffee 20oz", 
                                    active=True, code=code, expires=expires, difficulty=difficulty)
                 item.put()
         return self._test_location 
예제 #20
0
def get_lat_lng(address, silent=False):
    """
    address(unicode)からlat, lngを検索して返す
    silent = Trueだとエラーを出さない
    """
    addr_utf8 = smart_str(address)
    try:
        gmaps = GoogleMaps(GOOGLE_MAPS_API_KEY)
        lat, lng = gmaps.address_to_latlng(addr_utf8)
    except GoogleMapsError:
        if silent:
            return None, None
        raise
    return str(lat), str(lng)
예제 #21
0
 def __init__(self, thing_id=None, streetAddress=None, city=None, state=None, zipCode=None):
     googleMapsAddress = str(streetAddress) + " " + str(city) + " " + str(state) + " "+ str(zipCode)
     pprint.pprint( googleMapsAddress)
     gmaps = GoogleMaps(googleMapsApi_key)
     lat, lng = gmaps.address_to_latlng(googleMapsAddress)
     print lng
     print lat
     self.thing_id = thing_id
     self.latitude = lat
     self.longitude = lng
     self.zipCode = zipCode
     self.state = state
     self.city = city
     self.streetAddress = streetAddress
예제 #22
0
def retrieve():

    api_key = os.environ["X_GOOGLE_MAPS_API_Key"]  # api_key must be defined to POST/PUT.
    gmaps = GoogleMaps(api_key)

    try:
        os.makedirs(str(date.today()) + "/automatic")
    except:
        pass
    filename = str(date.today()) + "/automatic/address-coordinates.ttl"
    o = open(filename, "w")
    o.write("@prefix wgs: <http://www.w3.org/2003/01/geo/wgs84_pos#> .\n\n")
    provenance = open(str(date.today()) + "/automatic/address-coordinates.prov.ttl", "w")
    provenance.write(
        '''@prefix prov:          <http://www.w3.org/ns/prov#>.
@prefix foaf:          <http://xmlns.com/foaf/0.1/> .

<address-coordinates.ttl>
  prov:wasGeneratedBy [
    a prov:Activity, <https://raw.github.com/jimmccusker/twc-healthdata/master/data/source/healthdata-tw-rpi-edu/address-coordinates/version/retrieve.py>;

    prov:qualifiedAssociation [
      a prov:Association;
      prov:hadPlan <https://raw.github.com/jimmccusker/twc-healthdata/master/data/source/healthdata-tw-rpi-edu/address-coordinates/version/retrieve.py>;
    ]
    prov:used [
      prov:value """{sparql}""";
    ];
    prov:used <http://maps.googleapis.com/maps/api/geocode/>.

<https://raw.github.com/jimmccusker/twc-healthdata/master/data/source/healthdata-tw-rpi-edu/address-coordinates/version/retrieve.py> a prov:Plan;
  foaf:homepage <https://github.com/jimmccusker/twc-healthdata/blob/master/data/source/healthdata-tw-rpi-edu/address-coordinates/version/retrieve.py>.
'''.format(
            sparql=query
        )
    )

    endpointPrefix = endpoint + "?&format=text%2Fcsv&timeout=0&debug=on&"
    url = endpointPrefix + urllib.urlencode([("query", query)])
    header = None

    for line in csv.reader(urllib.urlopen(url), delimiter=","):
        if header == None:
            header = line
            continue
        addressURI = line[0]
        address = ", ".join([x for x in line[1:] if x != ""])
        lat, lng = gmaps.address_to_latlng(address)
        o.write(outputTemplate.format(uri=addressURI, lat=lat, lng=lng))
예제 #23
0
파일: workspace.py 프로젝트: pshirkey/dodah
 def do_post(self):
     
     address = self.param('address')
     miles = self.param('miles')
     max_results = self.param('max_results')
     if not max_results:
         max_results = 10
     values = { 'address':address, 'max_results':max_results,'miles':miles }
     if address and miles:
         gmaps = GoogleMaps(self.enviroment.google_maps_key)   
         lat, lng = gmaps.address_to_latlng(address)
         geoPoint = db.GeoPt(lat, lng)
         meters = float(miles) * base.METERS_IN_MILE        
         locations = models.Location.proximity_fetch( models.Location.all(), geoPoint, int(max_results), meters )
         values['locations'] = locations
     
     self.generate(FindLocations.template_name, values)
예제 #24
0
파일: views.py 프로젝트: wolvelopez/mitapa2
def obtpos(request):
    gmaps = GoogleMaps('AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A')
    #Distancia desde el lugar que te encuentras
    radio = '1000'
    #lugares que buscamos
    lugar = 'bar|cafeteria|comida|restaurante'
    if request.method == 'POST':
        formulario = lugaresCercanos(request.POST)
        if formulario.is_valid:
            direccion = request.POST['direccion']
            poblacion = request.POST['poblacion']
            direccion = direccion + ',' + poblacion
            print direccion
            radio = request.POST['radio_distancia']
            #utilizamos la libreria de google maps
            lat, lng = gmaps.address_to_latlng(direccion)
            lat = str(lat)
            lng = str(lng)
            print lat
            print lng
            lugares = 'https://maps.googleapis.com/maps/api/place/search/' + \
                'xml?location=' + lat + ',' + lng + '&radius=' + radio + \
                '&types=' + lugar + \
                '&sensor=true&key=AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A'
            print lugares
            xmldoc = minidom.parse(urllib.urlopen(lugares))
            local = []
            ref = []
            datos = []
            i = 0
            for item in xmldoc.getElementsByTagName("result"):
                for item in item.getElementsByTagName('name'):
                    local.append(item.firstChild.data)
                    print item.firstChild.data
                for item in xmldoc.getElementsByTagName("reference"):
                    ref.append(item.firstChild.data)
            #vamos a meter las listas en un diccionario para facilitar la
            #union en el template
            for i in range(0, len(local)):
                datos.append({'local': local[i], 'ref': ref[i]})
        return render_to_response('lugarescercanos.html', {'datos': datos},
        context_instance=RequestContext(request))
    else:
        formulario = lugaresCercanos()
        return render_to_response('direccion.html', {'formulario': formulario},
        context_instance=RequestContext(request))
예제 #25
0
파일: gmaps.py 프로젝트: NervosaX/reparser
    def get_distance_from_railways(self, address, max_distance=3, retry_wait=1):
        attempts = 0
        results = []

        while (True):
            gmaps = GoogleMaps()

            try:
                lat, lng = gmaps.address_to_latlng(address)
                local_search = gmaps.local_search('railway near ' + address)
            except GoogleMapsError:
                # Some sort of error occurred! Either the address is malformed,
                # or the server is having some sort of issue. We'll wait a little bit
                # and try again
                if attempts < self.max_attempts:
                    attempts += 1
                    # Wait 1 seconds before trying again
                    time.sleep(retry_wait)
                    logger.debug("... ... ... Failed to parse the address. Trying again. Attempt #" + attempts)
                    continue
                else:
                    logger.debug("... ... ... Failed all attempts. Skipping.")
                    return None            

            # Get our results
            for result in local_search['responseData']['results']:
                
                # Probably not accurate over this point... Weird things
                # can get in
                if int(result['accuracy']) > 5:
                    continue

                distance = self.haversine(lng, lat, 
                    float(result["lng"]), float(result["lat"]))

                data = {
                    'line_name': result['titleNoFormatting'],
                    'distance': round(distance, 2)
                }

                if (distance < max_distance):
                    results.append(data)

            return results
예제 #26
0
def retrieve(endpoint, api_key):
    
    gmaps = GoogleMaps(api_key)
    url = endpoint + '?' + urllib.urlencode([("query",query)]) + '&format=text%2Fcsv'
    header = None
    print >> sys.stderr, url
    
    for line in csv.reader(urllib.urlopen(url),delimiter=","):
        if header == None:
            header = line
            continue
        addressURI = line[0]
        address = ", ".join([x for x in line[1:] if x != ""])
        try:
           lat, lng = gmaps.address_to_latlng(address)
        except GoogleMapsError:
           print >> sys.stderr, 'GoogleMapsError'
        
        print '{},{},{}'.format(addressURI,lat,lng)
예제 #27
0
def select(paras):
	gmaps = GoogleMaps()
        address = paras['street']+", "+ paras['city']+", "+paras['state']
        latitude, longtitude = gmaps.address_to_latlng(address)
        print "Location convertion: " + str(latitude) + str(longtitude)
        time_start_mon = int(paras['s_mon'])
        time_start_day = int(paras['s_day'])
        time_start_hour = int(paras['s_hou'])
        time_end_mon = int(paras['e_mon'])
        time_end_day = int(paras['e_day'])
        time_end_hour = int(paras['e_hou'])
        radius = paras['r']
        start_time = datetime.datetime(2012, time_start_mon, time_start_day, time_start_hour, 0)
        end_time = datetime.datetime(2012, time_end_mon, time_end_day, time_end_hour, 0)
        start_epoch_time = time.mktime(start_time.timetuple()) * 1000
        end_epoch_time = time.mktime(end_time.timetuple()) * 1000
        distance = "3959*acos((sin({3}/57.29577951)*sin(latitude/57.29577951)+cos({3}/57.29577951)*cos(latitude/57.29577951)*cos(abs(longtitude-({2}))/57.29577951))) <{4}"
	querystr = ("select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} and " + distance + " order by user;").format(start_epoch_time, end_epoch_time, longtitude, latitude, radius)
	
	if (paras['r'] == '0'):
		querystr = ("select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} order by user;").format(start_epoch_time, end_epoch_time)
	print querystr	
	con, cur = sql_execute(querystr)
	
	data = []
	while True:
		dat = cur.fetchone()
		if dat == None:
			break
		data.append(dat)
	if (paras['type'] == '0'):
		return top_k_similar(data, paras['option1'], paras['option2'], paras['deadline'])
	if (paras['type'] == '1'):
		return mst.call_mst(data, paras['deadline'])
	if (paras['type'] == '2'):
		return kmeans_new.call_kmeans(data, paras['deadline'], int(paras['option1']))
	if (paras['type'] == '3'):
		return represent.call_represent(data, paras['deadline'], int(paras['option1']))
	else:
		return [], []
	pass
예제 #28
0
    def test_geocode(self):
        """Test googlemaps geocode() and address_to_latlng()"""

        addr = '1600 amphitheatre mountain view ca'
        gmaps = GoogleMaps(GMAPS_API_KEY)
        result = gmaps.geocode(addr)
        self.assertEqual(result['Status']['code'], 200)
        self.assertEqual(searchkey(result, 'CountryName'), 'USA')
        self.assertEqual(searchkey(result, 'PostalCodeNumber'), '94043')
        self.assertEqual(searchkey(result, 'ThoroughfareName'), '1600 Amphitheatre Pkwy')
        self.assertEqual(searchkey(result, 'LocalityName'), 'Mountain View')
        self.assertEqual(searchkey(result, 'AdministrativeAreaName'), 'CA')
        self.assertEqual(searchkey(result, 'CountryNameCode'), 'US')
        self.assertEqual(searchkey(result, 'address'), '1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA')
        lat, lng = searchkey(result, 'coordinates')[1::-1]
        self.assertAlmostEquals(lat,   37.422125, 3)
        self.assertAlmostEquals(lng, -122.084466, 3)

        (lat2, lng2) = gmaps.address_to_latlng(addr)
        self.assertAlmostEqual(lat, lat2, 3)
        self.assertAlmostEqual(lng2, lng2, 3)
예제 #29
0
파일: views.py 프로젝트: oleg-chubin/Cacard
def contacts(request):
    contacts = []
    gmaps = GoogleMaps('')
    for addr in Address.objects.all():
        lat, lng = gmaps.address_to_latlng(addr.address)
        contacts.append({'contact':addr,
                         'longitude': lng,
                         'latitude': lat})

    need_form = True
    if request.method == 'POST':
        form = ConsumerFeedback(request.POST)
        if form.is_valid():
            need_form = False
            form.save()
            return {'contacts': contacts, 'need_form': need_form}
    else:
        form = ConsumerFeedback()
    return {'contacts': contacts,
            'form': form,
            'need_form': need_form}
예제 #30
0
파일: helpers.py 프로젝트: mhfowler/LoveGov
def locationHelper(address, city, state, zip, location=None):

    if not location:
        location = PhysicalAddress()
        location.save()

    full_address = ''
    if address:
        full_address += address
    if city:
        if not full_address == '':
            full_address += ', '
        full_address += city
    if state:
        if not full_address == '':
            full_address += ', '
        full_address += state
    if zip:
        if not full_address == '':
            full_address += ', '
        full_address += zip

    location.address_string = address
    location.city = city
    location.state = state
    location.zip = zip

    gmaps = GoogleMaps(GOOGLEMAPS_API_KEY)
    coordinates = gmaps.address_to_latlng(full_address)
    latitude = coordinates[0]
    longitude = coordinates[1]
    location.latitude = latitude
    location.longitude = longitude
    location.save()

    setDistrict(location)

    location.setIdentifier()

    return location
예제 #31
0
    def migrate(self, data):
        "create geosound from v2 sound"
        
        # generate slug
        slug = slugify(data['title'])
        
        # get user
        ff_v2_user = User.objects.using('classic').get(pk=int(data['author_id']))
        user = DjangoUser.objects.using('default').get(username=ff_v2_user.username)
        
        # get created date
        import pytz
        created = pytz.timezone('America/New_York').localize(data['created'], is_dst=None)                
        
        # generate point from location
        from django.contrib.gis.geos import Point
        from googlemaps import GoogleMaps
        gmaps = GoogleMaps(settings.GOOGLE_API_KEY)
        try:
            lat, lng = gmaps.address_to_latlng(data['location'])
            point = Point(lng, lat, srid=4326)

            # save geosound
            geosound = GeoSound(sound="uploads/" + data['filename'], title=data['title'], location=data['location'], story=data['story'], created_by=user.username, user=user, slug=slug, point=point, created=created)
            geosound.save()

            # get tags
            tags = []
            if SoundsXTags.objects.using('classic').filter(sound_id=int(data['id'])).exists():
                tag_old_join_rows = SoundsXTags.objects.using('classic').filter(sound_id=int(data['id']))
                for tag_old_join_row in tag_old_join_rows:
                    tag = Tag.objects.using('classic').get(pk=tag_old_join_row.tag_id)
                    geosound.tags.add(tag.title)

            # connect the sound to the v3 collection
            v3_collection, created = Collection.objects.get_or_create(title='fantastic futures v2', defaults={'title': 'fantastic futures v2'})
            self.collections.add(v3_collection)
        except:
            pass
예제 #32
0
파일: workspace.py 프로젝트: pshirkey/dodah
 def do_post(self):
     id = self.param('id')
     entity = None
     if id and id != "":
         locForm = LocationForm(data=self.request.POST, instance=db.get(id))
     else:
         locForm = LocationForm(data=self.request.POST)        
     if locForm.is_valid():
         entity = locForm.save(commit=False)
         entity.owner = self.current_user
         entity.save() 
         id = entity.key()
         gmaps = GoogleMaps(self.enviroment.google_maps_key)   
         lat, lng = gmaps.address_to_latlng(entity.get_address())
         entity.update_location(db.GeoPt(lat, lng))
         entity.save()
     
     template_values = {
                            'loc':entity,
                            'form':locForm
                            }
     self.generate(EditLocation.template, template_values)
예제 #33
0
파일: views.py 프로젝트: wolvelopez/mitapa2
def nuevaTapaPosicion(request):
    #Lo primero es elegir el local de donde es la tapa
    gmaps = GoogleMaps('AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A')
    #Distancia desde el lugar que te encuentras
    radio = '1000'
    #lugares que buscamos
    lugar = 'bar|cafeteria|comida|restaurante'
    if request.method == 'POST':
        formulario = lugaresCercanos(request.POST)
        if formulario.is_valid:
            direccion = request.POST['direccion']
            poblacion = request.POST['poblacion']
            direccion = direccion + ',' + poblacion
            print direccion
            radio = request.POST['radio_distancia']
            #utilizamos la libreria de google maps
            lat, lng = gmaps.address_to_latlng(direccion)
            lat = str(lat)
            lng = str(lng)
            print lat
            print lng
            lugares = 'https://maps.googleapis.com/maps/api/place/search/xml? \
            location=' + lat + ',' + lng + '&radius=' + radio + '&types= \
            ' + lugar + '&sensor= \
            true&key=AIzaSyCNUf4Y4LBWWkQAYSvJmQCriCzNmEJkD0A'
            print lugares
            xmldoc = minidom.parse(urllib.urlopen(lugares))
            local = []
            for item in xmldoc.getElementsByTagName("result"):
                for item in item.getElementsByTagName('name'):
                    local.append(item.firstChild.data)
        return render_to_response('alttapa.html', {'local': local},
        context_instance=RequestContext(request))
    else:
        formulario = lugaresCercanos()
        return render_to_response('direccion.html', {'formulario': formulario},
        context_instance=RequestContext(request))
예제 #34
0
    def test_geocode(self):
        """Test googlemaps geocode() and address_to_latlng()"""

        addr = '1600 amphitheatre mountain view ca'
        gmaps = GoogleMaps(GMAPS_API_KEY)
        result = gmaps.geocode(addr)
        self.assertEqual(result['Status']['code'], 200)
        self.assertEqual(searchkey(result, 'CountryName'), 'USA')
        self.assertEqual(searchkey(result, 'PostalCodeNumber'), '94043')
        self.assertEqual(searchkey(result, 'ThoroughfareName'),
                         '1600 Amphitheatre Pkwy')
        self.assertEqual(searchkey(result, 'LocalityName'), 'Mountain View')
        self.assertEqual(searchkey(result, 'AdministrativeAreaName'), 'CA')
        self.assertEqual(searchkey(result, 'CountryNameCode'), 'US')
        self.assertEqual(
            searchkey(result, 'address'),
            '1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA')
        lat, lng = searchkey(result, 'coordinates')[1::-1]
        self.assertAlmostEquals(lat, 37.422125, 3)
        self.assertAlmostEquals(lng, -122.084466, 3)

        (lat2, lng2) = gmaps.address_to_latlng(addr)
        self.assertAlmostEqual(lat, lat2, 3)
        self.assertAlmostEqual(lng2, lng2, 3)
예제 #35
0
# How to get coordinates of address from Python
from googlemaps import GoogleMaps
gmaps = GoogleMaps(API_KEY)
lat, lng = gmaps.address_to_latlng(address)
예제 #36
0
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

# Replace for your own key
# https://developers.google.com/maps/documentation/javascript/tutorial#api_key
gmaps = GoogleMaps('AIzaSyAmEvPWMafJFafvXGR-ampYOLQVSWmP5xM')

kml = simplekml.Kml()

# CSV format
# username, tweet, location, profile pic, timestamp, number of tweets, number of followers, numbers of following

with open('demo.csv', 'rb') as csvfile:
    twitter_reader = unicode_csv_reader(csvfile)
    for row in twitter_reader:
        pnt = kml.newpoint()
        pnt.style.iconstyle.icon.href = "http://*****:*****@" + row[0] 
        pnt.description = row[1]
        address = row[2]
        lat, lng = gmaps.address_to_latlng(address)
        pnt.coords = [(lng, lat)]
        pnt.timestamp.when= row[4]

# Save the KML
kml.save("gangnam.kml")
예제 #37
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from googlemaps import GoogleMaps

gmaps = GoogleMaps()
address = u'東京'
lat, lng = gmaps.address_to_latlng(address.encode('utf-8'))
print lat, lng
예제 #38
0
reader = csv.reader(citiesDB)

# coordsList = []
# for row in reader:
# 	coords = {}
# 	coords['lat'] = float(row[0])
# 	coords['lng'] = float(row[1])
# 	weight = random.uniform(0,5)
# 	coordsList.append({"coords" : coords, "weight": weight})
# cities['locations'] = coordsList
# print cities
# citiesDB.close()

coordsList = []
for row in reader:
	coords = {}
	time.sleep(1)
	lat,lng = gmaps.address_to_latlng(row[0])
	print row[0],lat,lng
	coords['lat'] = lat
	coords['lng'] = lng
	weight = random.uniform(0,5)
	coordsList.append({"coords" : coords, "weight": weight})
cities['locations'] = coordsList
print cities
citiesDB.close()

f = open('locations.json', 'w')
f.write(json.dumps(cities))
f.close()
예제 #39
0
import codecs
import sys
from googlemaps import GoogleMaps

gmaps = GoogleMaps('ABQIAAAAbwWYBdNDWhSrlUDhnHoOzhRSZLIMLGsAILtzGCo_JdRkl29wtRTgPiY-xKbabP9VEHL8y3eZuIHvPw')

coops = json.load(codecs.open('./datos/Cooperativas.json', 'r', 'utf-8'))['rows']
calle, localidad , pais = 0,0,0

salida = []

for i, coop in enumerate(coops[:300]):
    direccion = "%s, %s %s" % (coop['Direccion'], coop['Localidad'], coop['PROVINCIA'])
    direccion = direccion.replace(u"Ñ", "N")
    try:
        lat, lng = gmaps.address_to_latlng(direccion)
        precision = 'calle'
        calle += 1
    except:
        direccion = "%s %s" % (coop['Localidad'], coop['PROVINCIA'])
        direccion = direccion.replace(u"Ñ", "N")
        try:
            lat, lng = gmaps.address_to_latlng(direccion)
            precision = 'localidad'
            localidad += 1
        except:
            print direccion
            lat,lng = -34.506132,-58.162336 #Rio de La Plata
            precision = 'pais'
            pais += 1
예제 #40
0
	adres 		= str(soup.body.find_all('li')[0].ul.li.nextSibling.nextSibling.nextSibling.nextSibling)
	adres		= adres[4:][:len(adres)-9]
	plaats 		= str(soup.body.find_all('li')[0].ul.li.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling)
	plaats 		= plaats[4:][:len(adres)-5]
	return adres + ' ' + plaats + ' , Netherlands'

member_companies 		= np.genfromtxt('input_data/link.csv', skip_header=False, delimiter=',', dtype='|S')
data 					= pandas.read_csv('input_data/link.csv', delimiter=',')
person_list 			= [['bart', 'gillz'], ['vincent','localsensor']]

	for person in member_companies: 
		output_person = list(person)
		if person[1] != 'none': 
			company_address 		= strip_tags(zoekBedrijf(person[1]))
			if company_address != 'none': 
				try: 
					lat, lng 				= gmaps.address_to_latlng(company_address)
					output_person.append(lat) 
					output_person.append(lng)
				except: 
					pass 
		print output_person


try:
    do_something()
except Exception:
    pass


예제 #41
0
N = 10000
addresses = {}

cursor.execute(query)
counter = 0
for row in cursor:
    #i#uname = str(row[0])
    text = str(row[0])
    regexMatch = re.search(currRegex, text, re.IGNORECASE)
    if not regexMatch == None:
        #print text[:140]
        addr = regexMatch.group(0)[3:]  #, text[:80]
        addr = addr.strip(punctuation).lower().strip()
        if ("the street" in addr) or ("my street" in addr) or (
                "this street" in addr) or ("our street" in addr) or (
                    "a street" in addr) or ("high street" in addr) or (
                        "upper st" in addr) or ("car park" in addr) or (
                            "the park" in addr) or ("in every" in addr):
            continue
        counter = counter + 1
        addresses[addr] = addresses.get(addr, 0) + 1
        #print addr

top_addr = sorted(addresses.iteritems(), key=itemgetter(1), reverse=True)[:N]
for addr, frequency in top_addr:
    #print "%s: %d" % (addr, frequency)
    lat, lng = gmaps.address_to_latlng(addr + ", london")
    print addr + ":" + frequency + ":" + lat + ":" + lng

print "\n", counter, "addresses identified."
            "dbname=PUSTACK user=postgres host=localhost password=tiger port=5433"
        )
        print "Connection successful"
    except:
        print "I am unable to connect to the database"

    cur = conn.cursor()
    table = 'keyword_identification_extraction'

    statement = "SELECT distinct page_no FROM " + table + " where keyword_type = '#2'"
    cur.execute(statement)
    page_number = cur.fetchall()

    gmaps = GoogleMaps('AIzaSyAfeD4ORUK_63ldCoIP13zQ7VW6zYXPdcM')
    address = 'India'
    lat_cent, lng_cent = gmaps.address_to_latlng(address)

    mymap = maps(lat_cent, lng_cent, 5)

    for pno in page_number:
        lat = []
        lng = []
        statement = "SELECT keyword FROM " + table + " where keyword_type = '#2' and page_no = " + str(
            pno[0])
        cur.execute(statement)
        rows = cur.fetchall()
        for row in rows:
            print row[0]
            address = row[0]
            try:
                lat, lng = gmaps.address_to_latlng(address)
예제 #43
0
#!/usr/bin/env python
# Foundations of Python Network Programming - Chapter 1 - search1.py
# Googlemaps API deprecated#
from googlemaps import GoogleMaps
# this will currently fail, needs api key
# gmaps = GoogleMaps(api_key)
gmaps = GoogleMaps()
address = '207 N. Defiance St, Archbold, OH'
print gmaps.address_to_latlng(address)