def lawnmower(lat1, lon1, lat2, lon2): '''Good for small distances only.''' SWEEP_SPACING = 3 #3m #Determine which way we are sweeping d1 = distance.haversine(lat1, lon1, lat1, lon2) d2 = distance.haversine(lat1, lon2, lat2, lon2) points = int(min(d1, d2) // SWEEP_SPACING) pts = [] if points != 0: modlat = True if d1 > d2: frac = (lat2 - lat1) / points else: frac = (lon2 - lon1) / points modlat = False for i in range(points): v1 = Coord(lat1 + frac * i, lon1) if modlat else Coord( lat1, lon1 + frac * i) v2 = Coord(v1.lat, lon2) if modlat else Coord(lat2, v1.lon) if i % 2: pts.append(v2) pts.append(v1) else: pts.append(v1) pts.append(v2) if not points % 2: pts.append(Coord(lat2, lon1) if modlat else Coord(lat1, lon2)) else: pts.append(Coord(lat1, lon1)) pts.append(Coord(lat2, lon2)) return pts
def lawnmower(lat1, lon1, lat2, lon2): '''Good for small distances only.''' SWEEP_SPACING = 3 #3m #Determine which way we are sweeping d1 = distance.haversine(lat1, lon1, lat1, lon2) d2 = distance.haversine(lat1, lon2, lat2, lon2) points = int(min(d1, d2)//SWEEP_SPACING) pts = [] if points != 0: modlat = True if d1 > d2: frac = (lat2 - lat1) / points else: frac = (lon2 - lon1) / points modlat = False for i in range(points): v1 = Coord(lat1 + frac*i, lon1) if modlat else Coord(lat1, lon1 + frac*i) v2 = Coord(v1.lat, lon2) if modlat else Coord(lat2, v1.lon) if i%2: pts.append(v2) pts.append(v1) else: pts.append(v1) pts.append(v2) if not points%2: pts.append(Coord(lat2, lon1) if modlat else Coord(lat1, lon2)) else: pts.append(Coord(lat1, lon1)) pts.append(Coord(lat2, lon2)) return pts
def main(a, b, c, d): values = Location.locate(a, b, c, d) first = distance.haversine(values[a], values[c]) second = distance.haversine(values[b], values[d]) print "The distance from", a, "to", c, "is", first, "miles" print "The distance from", b, "to", d, "is", second, "miles"
def spiral(c1, c2, c3=None): '''Good for small distances only.''' if c3 is None: c3 = c2 #Degenerates to a circle pattern data = [] start_radius = distance.haversine(c1.lat, c1.lon, c2.lat, c2.lon) end_radius = distance.haversine(c1.lat, c1.lon, c3.lat, c3.lon) start_angle = distance.bearing(c1.lat, c1.lon, c2.lat, c2.lon) end_angle = distance.bearing(c1.lat, c1.lon, c3.lat, c3.lon) earth_radius = 6378137 pts = [] climb_rate = min(1, c3.alt - c2.alt) #In m/revolution revs = int(ceil((c3.alt - c2.alt) / climb_rate)) if climb_rate != 0 else 1 radius_delta = (end_radius - start_radius) / revs #Radius increment/revolution print("REVS:", revs) for i in range(revs): j = 0 while j < 360: pct = (i + j / 360.0) / revs radius = start_radius + (end_radius - start_radius) * pct alt = c2.alt + (c3.alt - c2.alt) * pct angle = start_angle + (end_angle - start_angle) * pct offset_x = radius * cos(angle + distance.DTR(j)) offset_y = radius * sin(angle + distance.DTR(j)) data.append([offset_x, offset_y, alt]) offset_x /= earth_radius * cos(distance.DTR(c1.lat)) offset_y /= earth_radius pts.append( Coord(c1.lat + distance.RTD(offset_y), c1.lon + distance.RTD(offset_x), alt)) j += 360 / (2 * pi * radius / 4) pts.append(c3) data = np.array(data) fig = plt.figure() ax = Axes3D(fig) # Setting the axes properties ax.set_xlim3d([data[:, 0].min(), data[:, 0].max()]) ax.set_xlabel('Offset (m)') ax.set_ylim3d([data[:, 1].min(), data[:, 1].max()]) #ax.set_ylabel('Y') ax.set_zlim3d([data[:, 2].min(), data[:, 2].max()]) ax.set_zlabel('Altitude (m)') line = ax.plot(data[:1, 0], data[:1, 1], data[:1, 2])[0] plt.title("Spiral search pattern") line_ani = animation.FuncAnimation(fig, update_lines, MAX_ANIM, fargs=(data, line), interval=10, blit=False) plt.show() return pts
def getNear(mylat, mylong): servername = "mysql.dream.mmlab.gr" username = "******" password = "******" dbname = "dreammmlab_kapsali" myquery = "SELECT name, id, lat, lon, photo FROM beach" db = MySQLdb.connect(servername, username, password, dbname, charset="utf8", use_unicode=True) cur = db.cursor() json_return = {} try: cur.execute(myquery) items = [] names = [] lats = [] lons = [] ids = [] havs = [] phs = [] results = cur.fetchall() for item in results: if (haversine(float(item[3]), float(item[2]), float(mylong), float(mylat)) <= 15): names.append(item[0]) ids.append(int(item[1])) lats.append(float(item[2])) lons.append(float(item[3])) havs.append( haversine(float(item[3]), float(item[2]), float(mylong), float(mylat))) phs.append(item[4]) i = len(names) - 1 while i >= 0: myjson = { 'name': names[i], 'id': ids[i], 'latitude': lats[i], 'longitude': lons[i], 'distance': float(havs[i]), 'photo': phs[i] } items.append(myjson) i = i - 1 except Exception as error: return {'Error': str(error)} finally: cur.close() db.close() return jsonify(Items=items)
def calculate_distance(lat, long): country_list = preprocessing.import_data() nearest_distance = sys.maxint nearest_point = "" for point in country_list: point_distance = distance.haversine(float(long), float(lat), float(point[2]), float(point[1])) if nearest_distance > point_distance: nearest_distance = point_distance nearest_point = point[0] print nearest_point
def respond(update: Update, context: CallbackContext): print('message_id', update.message.text) logger.info(f'in handeler{update.message.text}') if update.message.text == None: lat = update.message.location.latitude lon = update.message.location.longitude address1 = (lon, lat) address2 = geocode(context.user_data['point_a']) distance = haversine(*address1, *address2) print("location", lon, lat) response = f'your distance from Hifa is:{distance}' elif len(update.message.text) > 0: context.user_data['place'] = update.message.text response = get_distance_from_hifa(context.user_data['place']) chat_id = update.effective_chat.id logger.info(f"= Got on chat #{chat_id}: {context.user_data['place']!r}") logger.info(f"= Got on chat #{chat_id}: {update.message}") context.bot.send_message(chat_id=update.message.chat_id, text=response)
def rentPropertyTraversal(listIds, univLoc, usrDist): #make a call to the rent.com listings.json endpoint, and get all the data required for interpretation. propCall = requests.get( ('http://rent.com/account/myrent/listings.json?ids=' + listIds), verify=False, timeout=50) propJSON = json.loads(propCall.text) #list comprehension technique here: this is actually a dictionary inside a list. refer to the values by key, properties = [{ 'url_path': x['url_path'], 'name': x['name'], 'address': x['address'], 'city': x['city'], 'state': x['state'], 'price_range': x['price_range'], 'bedroom_range': x['bedroom_range'], 'bathroom_range': x['bathroom_range'], 'image_url': x['image_url'] } for x in propJSON['listings']] for x in properties: try: propConn = requests.get(('http://rent.com' + x['url_path']), verify=False, timeout=50) except requests.exceptions.ConnectionError as e: message = 'Connection to {0} failed. \n {1}' print(message.format(x['url_path'], e.args[0].args[1].args[1])) propInfo = BeautifulSoup(propConn.text, "html.parser") geocode = propInfo.findAll(True, { "property": ['place:location:longitude', 'place:location:latitude'] }) x['dist_campus'] = distance.haversine(float(univLoc[1]), float(univLoc[0]), float(geocode[0]['content']), float(geocode[1]['content'])) #usrdist might be a string for some reason x['withinRange'] = True if x['dist_campus'] < usrDist else False # if x['withinRange']: # x['crime'] = crime.fetch(geocode[0]['content'], geocode[1]['content']) return properties
def on_message_received(msg): content_type, chat_type, chat_id = telepot.glance(msg) message = '' timestamp = datetime.datetime.fromtimestamp(msg['date']) print( timestamp.strftime('%d-%m-%Y %H:%M:%S') + ' Messaggio ricevuto da ' + msg['from']['first_name'] + ' ' + msg['from']['last_name']) if (content_type == 'text'): if msg['text'].lower() in COMMANDS: message = msg['text'] idx = COMMANDS.index(message) centralina = capoluoghi[idx] message = 'Centralina vicina: ' + centralina + '\n' misurazioni = read_centralina(centralina) message += misurazioni else: message = DEFAULT_MESSAGE elif (content_type == 'location'): #Invio coordinate latitude = msg['location']['latitude'] longitude = msg['location']['longitude'] centraline = read_csv_centraline() min_distance = 10000000000 nearest = '' for row in centraline: c_distance = distance.haversine(latitude, longitude, float(row['latitudine']), float(row['longitudine'])) if c_distance < min_distance: min_distance = c_distance nearest = row['centrale'] message = 'Centralina vicina: ' + nearest + '\n' misurazioni = read_centralina(nearest) message += misurazioni else: message = DEFAULT_MESSAGE bot.sendMessage(chat_id, message)
def elegxos_paralias(sname, slat, slon, addr, desc, s, ph): # !/usr/bin/python #-*- coding: iso-8859-7 -*- import MySQLdb import foursquare import sys reload(sys) # Reload does the trick! sys.setdefaultencoding('cp737') from para import krithrio_omoiothtas from distance import haversine from insert import goToTsek servername = "localhost" username = "******" password = "" dbname = "database" client = foursquare.Foursquare( client_id='0NKJU5YU3205AZXBGQWLDWRLREZRNBGWPDHYR2PXNFOFOGIY', client_secret='DIWIFQPLO0HLBBKOCYLAO1FRK5KA0DDGS1ZTVLN2RBSQST3E') db = MySQLdb.connect(servername, username, password, dbname, charset="utf8", use_unicode=True) cursor = db.cursor() sql1 = """SELECT id, lat, lon, name FROM beach""" cursor.execute(sql1) results = cursor.fetchall() lats = [] ids = [] names = [] lons = [] for row in results: id = row[0] lat = row[1] lon = row[2] name = row[3] lats.append(lat) names.append(name) lons.append(lon) ids.append(id) lats = [float(x) for x in lats] lons = [float(x) for x in lons] ids = [int(x) for x in ids] i = len(names) - 1 simularity = 0 while i >= 0: if haversine(slon, slat, lons[i], lats[i]) <= 1 and krithrio_omoiothtas( names[i], sname) >= 0.80 or haversine( slon, slat, lons[i], lats[i]) < 0.100: print 'simularity here' print sname print names[i] sql2 = """INSERT INTO beachplus (address, source, beach_id, alternate) VALUES (%s, %s, %s, %s)""" args2 = (addr, s, ids[i], sname) cursor.execute(sql2, args2) if s == 'terrabook.com': sqlp = """INSERT INTO photos(beach_id, ph) VALUES (%s, %s)""" if ph != []: for string in ph: cursor.execute(sqlp, (ids[i], string)) sql3 = """INSERT INTO description (beach_id, text, source) VALUES (%s, %s, %s)""" txt = '' for item in desc: txt = txt + item try: cursor.execute(sql3, (ids[i], txt, s)) except: txt = txt.encode('cp737', 'ignore') cursor.execute(sql3, (ids[i], txt, s)) db.commit() elif s == 'Foursquare': tip = client.venues.tips(desc) for item in tip["tips"]["items"]: tip_text = item["text"] sql6 = """INSERT INTO description(beach_id, text, source) VALUES(%s, %s, %s)""" args6 = (ids[i], tip_text, s) cursor.execute(sql6, args6) db.commit() venuephotos = client.venues.photos(desc, params={'group': 'venue'}) for photo in venuephotos["photos"]["items"]: photo_url = photo["prefix"] + "width500" + photo["suffix"] sqlph = """INSERT INTO photos (beach_id, ph) VALUES (%s, %s)""" cursor.execute(sqlph, (ids[i], photo_url)) db.commit() elif s == 'destinationskiathos.com': sql3 = """INSERT INTO description (beach_id, text, source) VALUES (%s, %s, %s)""" cursor.execute(sql3, (ids[i], desc, s)) sqlphoto = """INSERT INTO photos (beach_id, ph) VALUES (%s, %s)""" cursor.execute(sqlphoto, (ids[i], ph)) db.commit() elif s == 'cleanbeaches.gr': sql3 = """INSERT INTO description (beach_id, text, source) VALUES (%s, %s, %s)""" cursor.execute(sql3, (ids[i], desc, s)) db.commit() else: sql3 = """INSERT INTO description (beach_id, text, source) VALUES (%s, %s, %s)""" cursor.execute(sql3, (ids[i], desc, s)) if ph != []: for item in ph: sqlph = """INSERT INTO photos (beach_id, ph) VALUES (%s, %s)""" cursor.execute(sqlph, (ids[i], item)) db.commit() db.commit() simularity = simularity + 1 i = i - 1 db.close() return simularity
def distance(self, otherPoint): # Haversine does the conversion to radians. return distance.haversine([self.deg_lat, self.deg_lon], [otherPoint.deg_lat, otherPoint.deg_lon])
if((gpsy<ltu and gpsy>ltd) or(gpsx>lgl and gpsx<lgr)): print("Car has entered region"+" "+y) if(aprz>=1 and aprz<=16): y=str(aprz) lat=data[T][y]["exit"]["lat"] lng=data[T][y]["exit"]["lng"] print (lat,lng) ltu = lat+deglt ltd = lat-deglt lgl = lng-long(lat,x) lgr = lng+long(lat,x) print(ltu,ltd,lgl,lgr) print(gpsx,gpsy) if((gpsy<ltu and gpsy>ltd) or(gpsx>lgl and gpsx<lgr)): print("Car is exiting zone"+" "+y) if(aprz<16): aprz+=1 else: aprz=1 for i in range(0,4): tempx=x[i] tempy=y[i] d=haversine(lng,lat,tempx,tempy) print(d)
def test_haversine(self): expected = 157425 actual = int(haversine((1, 1), (0, 0))) self.assertEqual(expected, actual)
def main(argv): if len(argv) < 5: print "Usage: example.py api_url consumer_key consumer_secret authorized_token authorized_token_secret" return 1 api_url = argv[0] consumer_key = argv[1] consumer_secret = argv[2] authorized_token = argv[3] authorized_token_secret = argv[4] oauth_credential = tripit.OAuthConsumerCredential(consumer_key, consumer_secret, authorized_token, authorized_token_secret) t = tripit.TripIt(oauth_credential, api_url = api_url) future_trips = t.list_trip({ 'past': 'false', 'page_size': 100 }).get_children()[:-1] past_trips = t.list_trip({ 'past': 'true', 'page_size': 100 }).get_children()[:-1] trips = [] for trip in sorted(future_trips+past_trips): start_date = trip.get_attribute_value("start_date") # ignore all trips before going homeless if start_date.isoformat() < "2012-08-30": continue end_date = trip.get_attribute_value("end_date") location = trip.get_attribute_value("primary_location") primary_location = trip.get_children()[1] latitude = float(primary_location.get_attribute_value("latitude")) longitude = float(primary_location.get_attribute_value("longitude")) trip = Trip(start_date, end_date, location, latitude, longitude) trips.append(trip) # This all started from Edinburgh previous_trip = Trip(0, 0, "Edinburgh, United Kingdom", 55.9500, 3.2200) total_distance = 0 print "To\tStart Date\tEnd Date\tTravelled distance" for trip in trips: distance = 0 if previous_trip: distance = haversine(previous_trip.longitude, previous_trip.latitude, trip.longitude, trip.latitude) print "%s\t%s\t%s\t%s" % (trip.location, trip.start_date, trip.end_date, distance) previous_trip = trip total_distance += distance print "Total travelling distance %s" % total_distance print "<table>" print "<tr><td>To</td><td>Start Date</td><td>End Date</td><td>Travelled distance</td></tr>" for trip in trips: distance = 0 if previous_trip: distance = haversine(previous_trip.longitude, previous_trip.latitude, trip.longitude, trip.latitude) print "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (trip.location, trip.start_date, trip.end_date, int(distance)) previous_trip = trip total_distance += distance print "</table>"
def test_type_of_result(): lat1, lon1 = 48.865070, 2.380009 lat2, lon2 = 48.8609473, 2.3646878 assert type(haversine(lon1, lat1, lon2, lat2)) is float