コード例 #1
0
def obtain_alternatives(trip_id, user_id):
	db = get_trip_db()
	trip = E_Mission_Trip.trip_from_json(db.find_one({"trip_id": trip_id, "user_id": user_id}))
	logging.debug(trip.sections)
	start_coord = trip.trip_start_location.maps_coordinate()
	end_coord = trip.trip_end_location.maps_coordinate()
	logging.debug("Start: %s " % start_coord)
	logging.debug("End: %s " % end_coord)
	    
	curr_time = datetime.datetime.now()
	curr_month = curr_time.month
	curr_day = curr_time.day
	curr_hour = curr_time.hour
	curr_minute = curr_time.minute

	otp_modes = ['CAR', 'WALK', 'BICYCLE', 'TRANSIT']
	
        for mode in otp_modes:
                try:
		    otp_trip = OTP(start_coord, end_coord, mode, write_day(curr_month, curr_day, "2015"), write_time(curr_hour, curr_minute), False)
     		    otp_trip = otp_trip.turn_into_trip(None, user_id, trip_id) 
		    otp_trip.save_to_db()
                except Exception as e:
                    #modes = ['driving', 'walking', 'bicycling', 'transit']
                    logging.debug("Got error %s from OTP, defaulting to Google Maps" % e)
                    otp_to_google_mode = {"CAR":"driving", "WALK":"walking", "BICYCLE":"bicycling", "TRANSIT":"transit"}
                    mode = otp_to_google_mode[mode]
                    gmaps = googlemaps.GoogleMaps('AIzaSyBEkw4PXVv_bsAdUmrFwatEyS6xLw3Bd9c')
                    result = gmaps.directions(origin=start_coord, destination=end_coord, mode=mode)
                    gmaps_trip = google_maps_to_our_trip(result, None, user_id, trip_id, mode, curr_time)
                    gmaps_trip.save_to_db()

        '''
コード例 #2
0
def get_distance_ville(v1, v2, engine):
    global static_google_maps
    file = "memory\\html_%s_%s_%s.html" % (engine, v1, v2)
    if os.path.exists(file):
        f = codecs.open(file, "r", "utf-8")
        r = f.read()
        f.close()
        return r
    else:
        if engine == "mappy":
            url = "http://fr.mappy.com/itinerary_homepage#d%5B%5D=#V1#,+France&d%5B%5D=#V2#,+France&ipo=1&lm=r&p=itinerary"
            url = url.replace("#V1#", v1)
            url = url.replace("#V2#", v2)
            param = ""
            r = get_page_html(url, param)
        elif engine == "cara":
            url = "http://www.caradisiac.com/service/itineraire/"
            param = "iti-start-way=&iti-start-postal_code=&iti-start-town=%s&iti-start-country_code=France&iti-end-way=&iti-end-postal_code=&iti-end-town=%s&iti-end-country_code=France"
            param = param % (v1.lower(), v2.lower())
            r = get_page_html(url, param)
        elif engine == "googlemaps":
            h = random.randint(100, 200) * 1.0 / 1000
            time.sleep(h)
            if static_google_maps == None:
                static_google_maps = googlemaps.GoogleMaps(
                    api_key="ABQIAAAA3LCD_QWHgQyYWMUdx1mKtRTOLnapKzarYQ7apQ46S420-wKw2BQiR10GuPti7gX9-PpvG3ttFYn4Uw")
            try:
                x = static_google_maps.directions(v1, v2)
            except googlemaps.GoogleMapsError, e:
                raise Exception("unable to get direction for " +
                                v1 + "," + v2 + "\n" + str(e))
            r = str(x)
        else:
コード例 #3
0
def _getGmapsInstance():
    """get a google maps wrapper instance"""
    key = constants.GOOGLE_PLACES_API_KEY
    if key is None:
        log.error("a google API key is needed for using the Google maps services")
        return None
        # only import when actually needed
    import googlemaps
    gMap = googlemaps.GoogleMaps(key)
    return gMap
コード例 #4
0
 def getGmapsInstance(self):
     """get a google maps wrapper instance"""
     key = constants.GOOGLE_API_KEY
     if not key:
         print(
             "onlineServices: a google API key is needed for using the google maps services"
         )
         return None
         # only import when actually needed
     import googlemaps
     gMap = googlemaps.GoogleMaps(key)
     return gMap
コード例 #5
0
def get_avg_time(employee_zips, local_zips):

    #open a google maps cient
    gmaps = googlemaps.GoogleMaps(api_key)

    #if error file already exists, load it into error list
    try:
        print "uploading previous error list"
        f = open(error_file, "r")
        prev_errors = csv.reader(f)
        error_zips = list()
        for row in prev_errors:
            error_zips.append(row)
    except:
        #create header for error list
        error_zips = [[
            'Start Zip', 'End Zip', 'Employees', 'Error Message', 'Duration'
        ]]

    #initialize count and define continuous error limit
    error_count = 0
    error_limit = 10

    #Go through every possible ideal zip
    for zipcode in local_zips:

        #if data isnt already there
        if len(zipcode) < 2:

            print ""
            print "Driving Durations if location was moved to " + zipcode[0]

            #initialize time and commuters for possible ideal zip
            total_time = 0
            commuters = 0

            #for every likely driver zipcode
            for index in range(len(employee_zips)):

                #start zip is the zip of driver, end zip is the possible ideal zip
                start = employee_zips[index][0]
                end = zipcode[0]

                #if they are not the same zip
                if start is not end:

                    #try to use googlemaps
                    try:
                        #get driving duration in minutes
                        directions = gmaps.directions(start, end)
                        minutes = directions['Directions']['Duration'][
                            'seconds'] / 60.0
                        print str(employee_zips[index][1]
                                  ) + " would commute %.2f minutes" % minutes

                        #multiple duration by number of employees in starting zip
                        minutes = minutes * float(employee_zips[index][1])
                        #accumulate time
                        total_time = total_time + minutes
                        #accumulate commuters
                        commuters = commuters + float(employee_zips[index][1])
                        #reset error counter bc of success
                        error_count = 0
                    #if googlemaps fails, handle error
                    except:
                        #record error name
                        error = sys.exc_info()[0]
                        #record commuters in zip
                        commuters_in_zip = float(employee_zips[index][1])
                        #add zips, commuters, and error to error list
                        error_zips.append(
                            [start, end, commuters_in_zip, error])
                        print "Error calculating duration from %s to %s, added to error list" % (
                            start, end)

                        #play audible horn to signify error
                        pygame.mixer.music.load(horn)
                        pygame.mixer.music.play()
                        while pygame.mixer.music.get_busy() == True:
                            continue

                        #increase error counter
                        error_count = error_count + 1

                        #if too many errors in a row, save files and quit script
                        if error_count > error_limit:
                            print "Too many continuous errors, saving files and quiting script..."

                            #save files
                            with open(output_file, "wb") as f:
                                writer = csv.writer(f)
                                writer.writerows(local_zips)

                            with open(error_file, "wb") as f:
                                writer = csv.writer(f)
                                writer.writerows(error_zips)

                            #quit function
                            return

                #if start zip is the same as end zip, do nothing to time, but add commuters
                elif start is end:
                    commuters = commuters + float(employee_zips[index][1])

                #sleep half sec to ensure script does not violate google limits
                time.sleep(0.5)

            #once done with all possible drivers, calculate average time for ending zip, add time and commuters to that zips list
            avg_time = total_time / commuters
            zipcode.append(avg_time)
            zipcode.append(commuters)

            print "Average time for %s is %.2f minutes\n" % (zipcode[0],
                                                             avg_time)

            #save output and error files
            with open(output_file, "wb") as f:
                writer = csv.writer(f)
                writer.writerows(local_zips)

            with open(error_file, "wb") as f:
                writer = csv.writer(f)
                writer.writerows(error_zips)

            #play audible ding to signify success
            pygame.mixer.music.load(ding)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy() == True:
                continue

    return
コード例 #6
0
'''
Created on 15-09-2012

@author: i2
'''
import googlemaps

PKWs = [
    "ul.Dluga 40/42 , Konstancin-Jeziorna",
    "ul. Wojewodzka 12 , Konstancin-Jeziorna",
    "ul. Zeromskiego 15 , Konstancin-Jeziorna",
    "ul.J.Sobieskiego 6 , Konstancin-Jeziorna",
    "ul. Wilanowska 1 , Konstancin-Jeziorna",
    "ul.Jaworskiego 18 , Konstancin-Jeziorna",
    "ul.Bielawska 57 , Konstancin-Jeziorna",
    "ul. Szkolna 7 , Konstancin-Jeziorna",
    "ul. K.Pulaskiego 72 , Konstancin-Jeziorna", "ul. Wspolna 1/3 , Bielawa",
    "ul. Rycerska 13 , Konstancin-Jeziorna"
]
g = googlemaps.GoogleMaps()
i = 0
coords = []
for PKW in PKWs:
    i += 1
    a = g.address_to_latlng(PKW)
    coords.append("POINT(" + str(a[0]) + " " + str(a[1]) + ")")
    Visum.Net.AddZone(i, str(a[1]), str(a[0]))
コード例 #7
0
#
#Description of script:
# Simple script to get duration of a drive, one drive at a time
# Script contains error handling for start and end points that do not work in google maps
#   1. Asks user for start and end point
#   2. Calculates duration, prints out
#   3. Asks user if it wants to do another request
#
####################################################################################

import googlemaps
import pygame

#set up google maps
api_key = 'AIzaSyBkfNH9_w6wPbWrzmSnxxVXvOvzuVj0b7s'
gmaps = googlemaps.GoogleMaps(api)

#sounds to be used for notifications
ding = '../../sounds/ding.wav'
horn = '../../sounds/bike_horn.wav'
pygame.mixer.init()


#function to play a sound
def play_sound(wav_file):

    pygame.mixer.music.load(wav_file)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy() == True:
        continue