Exemple #1
0
def school_histogram(filename):
    key = os.getenv('GOOGLE_MAPS_API_KEY')
    df = pd.read_excel(filename)

    df.columns = [
        'school', 'grade', 'res_addr', 'pickup_time', 'pickup_bus',
        'pickup_location', 'pickup_stop', 'pickup_stop_desc', 'dropoff_time',
        'dropoff_bus', 'dropoff_location', 'dropoff_stop', 'dropoff_stop_desx',
        'pickup_dist_from_stop', 'dropoff_dist_from_stop'
    ]

    # School: [Drop Off, Start Time, End Time]
    school_time = {
        "ALT": ["09:20", "09:30", "14:15", "115 A St."],
        "BAR": ["08:50", "09:05", "15:05", "100 Dudley Rd."],
        "BRO": ["09:00", "09:15", "15:15", "575 Pleasant St."],
        "CAM": ["07:55", "08:15", "14:25", "215 Elm St."],
        "CHA": ["08:00", "08:30", "15:30", "139 Newbury St"],
        "DUN": ["08:50", "09:05", "15:05", "48 Frost St."],
        "FHS": ["07:00", "07:25", "13:55", "115 A St."],
        "FUL": ["07:55", "08:15", "14:25", "31 Flagg Dr."],
        "HEM": ["09:00", "09:15", "15:15", "729 Water St."],
        "JUN": ["00:00", "00:00", "00:00",
                "29 Upper Joclyn Ave."],  # NEEDS VERIFICATION
        "KNG": ["09:10", "09:25", "15:25", "454 Water St."],
        "MAR": ["07:18", "07:20", "13:45", "273 Union Ave."],
        "MCC": ["08:00", "08:15", "14:15", "8 Flagg Dr."],
        "POT": ["09:00", "09:15", "15:15", "492 Potter Rd."],
        "STA": ["08:50", "09:05", "15:05", "25 Elm St."],
        "STB": ["07:45", "08:00", "14:15", "832 Worcester Rd"],
        "WAL": ["07:55", "08:15", "14:25", "301 Brook St."],
        "WIL": ["08:50", "09:05", "15:05", "169 Leland St."]
    }

    # School: [pickup_time1, pickup_time2, pickup_time3, etc.]
    school_dict = dict()
    df = df.dropna(subset=['pickup_time'])
    break_counter = 0

    for index, row in df.iterrows():
        school = row["school"]
        time = datetime.strptime(row["pickup_time"], '%I:%M %p')
        am_dest = row["pickup_stop_desc"]
        pm_dest = row["dropoff_stop_desx"]

        if school not in school_dict:
            school_dict[school] = [[time.timestamp(), am_dest, pm_dest]]
        else:
            school_dict[school] += [[time.timestamp(), am_dest, pm_dest]]

    for y in school_dict:
        gmap = gmplot.GoogleMapPlotter(42.2981, -71.4361, 15)
        gmap.apikey = key

        if break_counter < 100:
            break_counter += 1

            school_times = [item[0] for item in school_dict[y]]
            time_stamps = school_times

            earliest_pickup = datetime.fromtimestamp(min(
                time_stamps)).strftime("%Y-%m-%d %H:%M:%S").split(" ")[1][:-3]
            latest_pickup = datetime.fromtimestamp(max(time_stamps)).strftime(
                "%Y-%m-%d %H:%M:%S").split(" ")[1][:-3]
            average_pickup = datetime.fromtimestamp(
                sum(time_stamps) / len(time_stamps)).strftime(
                    "%Y-%m-%d %H:%M:%S").split(" ")[1][:-3]

            subtitle = "Earliest Pickup: " + earliest_pickup + " | Latest Pickup: " + latest_pickup +\
                       " | Average Pickup: " + average_pickup + " | Drop Off Time: " + school_time[y][0] + " | Start Time: " + school_time[y][1]

            fig, ax = plt.subplots()

            # create 10 bins evenly spaced out between first and last pickup time per school
            counter = min(time_stamps)
            step = (max(time_stamps) - min(time_stamps)) / 10.0
            calculated_bins = [counter]
            for x in range(10):
                counter += step
                calculated_bins += [counter]

            # plot histogram
            (n, bins, patches) = ax.hist(time_stamps,
                                         color="skyblue",
                                         bins=calculated_bins,
                                         rwidth=0.8)
            ax.set_xticks(calculated_bins)

            back_to_date = []
            for x in bins:
                back_to_date += [
                    datetime.fromtimestamp(x).strftime(
                        "%Y-%m-%d %H:%M:%S").split(" ")[1][:-3]
                ]

            ax.set_xticklabels(back_to_date)
            ax.xaxis.set_minor_locator(tkr.AutoMinorLocator(n=2))
            ax.xaxis.set_minor_formatter(tkr.FixedFormatter(back_to_date))
            ax.xaxis.set_major_formatter(tkr.NullFormatter())

            for tick in ax.xaxis.get_minor_ticks():
                tick.tick1line.set_markersize(0)

            title = "School Pickup Data for " + str(y)
            plt.suptitle(title, fontsize=14)
            plt.title(subtitle, fontsize=6.5)
            plt.xlabel("Time")
            plt.ylabel("Number of Students")

            plt.show()

            # below is for plotting points on map
            # retrieving data points within each of the histogram bins
            binlist = np.c_[bins[:-1], bins[1:]]
            d = np.array(time_stamps)
            list_time = []
            for i in range(len(binlist)):
                if i == len(binlist) - 1:
                    l = d[(d >= binlist[i, 0]) & (d <= binlist[i, 1])]
                else:
                    l = d[(d >= binlist[i, 0]) & (d < binlist[i, 1])]
                list_time += [l.tolist()]

            school_info = school_dict[y]
            bin_dict = {i: list_time[i] for i in range(0, len(list_time))}
            pickup_dict = {i: [] for i in range(0, len(list_time))}

            for x in school_info:
                for n in range(10):
                    if x[0] in bin_dict[n]:
                        pickup_dict[n] += [(x[1]).replace('*', '')]

            for key in pickup_dict:
                pickup_dict[key] = list(set(pickup_dict[key]))

            lat_dict = {i: [] for i in range(0, 10)}
            lon_dict = {i: [] for i in range(0, 10)}

            for key in pickup_dict:
                for value in pickup_dict[key]:
                    pickup_coordinates = get_coordinates(value)
                    if pickup_coordinates[0] is not None and pickup_coordinates[
                            1] is not None:
                        lat_dict[key] += [pickup_coordinates[0]]
                        lon_dict[key] += [pickup_coordinates[1]]

            # Place map
            colors = [
                "#ffffff", "#ecd8e9", "#d8b1d4", "#c38bbf", "#ad66a9",
                "#973e95", "#800080", "#6a0c6a", "#551054", "#411140",
                "#2d102c"
            ]
            for x in range(10):
                gmap.scatter(lat_dict[x],
                             lon_dict[x],
                             color=colors[x],
                             size=150,
                             marker=False)

            school_location = get_coordinates(school_time[y][-1])
            school_lat_coordinates = [school_location[0]]
            school_lon_coordinates = [school_location[1]]
            gmap.scatter(school_lat_coordinates,
                         school_lon_coordinates,
                         color=colors[10],
                         size=300,
                         marker=False)

            gmap.draw("pickup_" + str(y) + ".html")
 def ready_direction_array(self):
     self.direction_array = self.client.dir_points
     gmap = gmplot.GoogleMapPlotter(52.29661, 19.45500, 5)
     lat, lng = zip(*self.direction_array)
     gmap.plot(lat, lng)
     gmap.draw("dirs.html")
Exemple #3
0
import csv
from gmplot import gmplot
from generateCoordinates import generateCoordsWithinSquare
import json
from pprint import pprint
import os

meterWidth = 5000
count = meterWidth / 30

# Open up json from eventful result
data = json.load(open('EventfulQueries/nextWeek200Popular.json'))
events = data["events"]["event"]
for event in events:
    venue_name = event["venue_name"]
    directory = "Venues/" + venue_name
    latitude = float(event["latitude"])
    longitude = float(event["longitude"])
    gmap = gmplot.GoogleMapPlotter(latitude, longitude, 13)
    map_file = directory + "/map.html"

    # Store gps data to collect in a file, and visual map in map.html
    if not os.path.exists(directory):
        os.makedirs(directory)
    data = generateCoordsWithinSquare(latitude, longitude, meterWidth, count,
                                      gmap, map_file)
    data["center_point"] = [latitude, longitude]
    filename = directory + "/data_to_collect.json"
    with open(filename, 'w') as fp:
        json.dump(data, fp, indent=4, sort_keys=True)
Exemple #4
0
from ast import literal_eval
from gmplot import gmplot
import random
import os

trainSet = pd.read_csv(
    '../train_set.csv',  # replace with the correct path
    converters={"Trajectory": literal_eval},
    index_col='tripId')

directory = 'map'
if not os.path.exists(directory):
    os.makedirs(directory)

items = random.sample(range(len(trainSet)), 5)
for item in items:
    traj = traj = trainSet['Trajectory'].iloc[item]
    lon = []
    lan = []
    for i in traj:
        lon.append(i[1])
        lan.append(i[2])

    gmap = gmplot.GoogleMapPlotter(lan[0], lon[0], len(lon))

    gmap.plot(lan, lon, 'green', edge_width=5)

    gmap.draw(directory + '/map_' +
              str(trainSet['journeyPatternId'].iloc[item]) + '_' + str(item) +
              '.html')
Exemple #5
0
def gmap_plot(gps_lat, gps_lon, filename):
    gmap = gmplot.GoogleMapPlotter(gps_lat[0], gps_lon[0], 20)
    gmap.plot(gps_lat, gps_lon, 'cornflowerblue', edge_width=10)
    # Draw
    gmap.draw(filename +".html")
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 19:19:34 2019

@author: Rudrajit
"""

import csv
from gmplot import gmplot

gmap = gmplot.GoogleMapPlotter(28.689169, 77.324448, 17)

gmap.coloricon = "http://www.googlemapsmarkers.com/v1/%s/"

with open("route.csv", "r") as f:
    reader = csv.reader(f)
    k = 0

    for row in reader:
        lat = float(row[0])
        long = float(row[1])
        if (k == 0):
            gmap.marker(lat, long, 'yellow')
            k = 1
        else:
            gmap.marker(lat, long, 'blue')

gmap.marker(lat, long, 'red')

gmap.draw("mymap.html")
Exemple #7
0
		#print path
		#print "122222222222222222222222222211111111111111111111"

	#for  d  in dist:
	#	print d[0]
	final_dist = sort(dist)
	#for  d  in dist1:
	#	print (d[0],d[1],d[2])
	
	count = 0
	generic = 0
	for d in final_dist:
		if count == 5 :
			break

		gmap = gmplot.GoogleMapPlotter(d[3][0][1],d[3][0][0],13)
		#print d[2][0][1]
		#print d[2][0][0]

		longitude , latitude = zip(*d[3])
		#print "-------------------------lat1------------------------"
		#print longitude
		#print "-------------------------end of lat 1-----------------"
		longitude2, latitude2 = zip(*d[1]) 	
		#print "---------------------------lat2-------------------------"
		#print longitude2		
		#print "---------------------------end of lat 2-------------------"
		#print latitude2
		#print latitude
		#print longitude
Exemple #8
0
for i in range(sheet.nrows):

    if str(type(sheet.cell_value(i, 9))) == "<class 'float'>" and str(
            type(sheet.cell_value(i, 8))) == "<class 'float'>":
        longitude.append(sheet.cell_value(i, 9))
        latitude.append(sheet.cell_value(i, 8))

#Your Google_API_Key

y_12 = latitude
x_12 = longitude
#Import important libraries
from gmplot import gmplot

# Place map
gmap = gmplot.GoogleMapPlotter(y_12[0], x_12[0], 13)

# Polygon

# gmap.plot(latitude, longitude, 'cornflowerblue', edge_width=10)

# Scatter points
gmap.coloricon = "http://www.googlemapsmarkers.com/v1/%s/"

gmap.scatter(latitude, longitude, '#3B0B39', size=10, marker=False)

# Marker
hidden_gem_lat, hidden_gem_lon = 37.770776, -122.461689
for index, value in enumerate(latitude):
    gmap.marker(latitude[index], longitude[index], 'cornflowerblue')
gmap.apikey = key
## Plotting in Google Maps

## https://github.com/vgm64/gmplot
#pip install gmplot
from gmplot import gmplot
# Google_API_Key is the custom file name I gave to my key
from Google_API_Key import api_key as google_key

STL = gmaps.geocode('St. Louis')
STL[0]['geometry']['location']

## latitutde and longitude and "zoom level"
## or location and zoom level (deprecated)

plot1 = gmplot.GoogleMapPlotter(38.6270025, -90.19940419999999, 13)
plot1.apikey = google_key

stl_places = [
    "Forest Park, St. Louis", "Missouri Botanical Garden, St. Louis",
    "Anheuser Busch, St. Louis", "Arch, St. Louis"
]


def grab_latlng(place):
    x = gmaps.geocode(place)
    return (x[0]["geometry"]["location"]["lat"],
            x[0]["geometry"]["location"]["lng"])


l = [grab_latlng(i) for i in stl_places]
Exemple #10
0
def getGPS(frameid=0):
    if (video_type == 0):
        out = ''
        ynDATA = False
        dataE1, dataE2 = 0.0, 0.0
        dataN1, dataN2 = 0.0, 0.0

        try:
            while (serial.inWaiting()):
                out = str(serial.readline().decode('utf-8'))

        except:
            pass

        if out != '':
            gpsdata = out.split(",")
            print(out)

            if (gpsdata[0] == "$GPRMC"):
                dataE = gpsdata[5]
                dataN = gpsdata[3]
                if (len(dataE) >= 10):
                    dataE1, dataE2 = float(dataE[:3]), float(dataE[3:])
                    gpsE = dataE1 + dataE2 / 60
                    ynDATA = True
                if (len(dataN) >= 9):
                    dataN1, dataN2 = float(dataN[:2]), float(dataN[2:])
                    gpsN = dataN1 + dataN2 / 60

        str_gpsE = str(gpsE)
        str_gpsN = str(gpsN)

    else:
        ynDATA = False
        for i in range(0, len(gps_frames) - 1):
            if (frameID >= int(gps_frames[i][0])
                    and frameID < int(gps_frames[i + 1][0])):
                print(frameID, gps_frames[i][0], gps_frames[i][1])

                gpsN, gpsE = gps_frames[i][1].split(",")
                ynDATA = True

        #now_loc = (float(gpsE), float(gpsN))
        gmap = gmplot.GoogleMapPlotter(float(gpsN), float(gpsE), 18)
        print("GPS:", float(gpsN), float(gpsE))
        if (float(gpsN) > 0) and float(gpsE) > 0:
            # Marker
            print(gpsN, gpsE)
            #gmap.plot(float(gpsN), float(gpsE), 'cornflowerblue', edge_width=10)
            gmap.marker(float(gpsN),
                        float(gpsE),
                        color='#000000',
                        c=None,
                        title="Defect")
            #gmap.scatter(float(gpsE), float(gpsN),'#FF6666', edge_width=10)
            # Draw
            #gmap.coloricon = "pointer.png"
            gmap.apikey = 'AIzaSyCbQibjl5FKhsQCFz8lj1ad3qru1bUCdrU'
            gmap.draw("my_map.html")

            #print(gpsN, gpsE)

    return ynDATA, float(gpsE), float(gpsN)




#find mean latitude and longitude to center the map
cam_longitudes = [camera['location'][0] for camera in camera_coordinates]
cam_latitudes = [camera['location'][1] for camera in camera_coordinates]

mean_cam_latitude = np.mean(cam_latitudes)
mean_cam_longitude = np.mean(cam_longitudes)

print(f'mean_cam_latitude : {mean_cam_latitude} \nmean_cam_longitude : {mean_cam_longitude}')

#place map
gmap = gmplot.GoogleMapPlotter(mean_cam_latitude, mean_cam_longitude, 13)


for taxi in taxi_path:
    gmap.scatter([taxi['latitude']], [taxi['longitude']], color='black',  marker = False, size = 1,title=str(taxi['longitude']) + '-' +str(taxi['latitude']))

#plotting sample of cameras and detected points on map
for camera in camera_coordinates:
    cam_latitude, cam_longitude = camera['location'][1], camera['location'][0]
    gmap.marker(cam_latitude, cam_longitude, color='green', title=camera['id'])
    gmap.scatter([cam_latitude], [cam_longitude], color='yellow', marker = False, size=50)
    #only including cameras that detect atleast one vehicle
    if str(camera['id']) in camera_stream:
        detected_vehicles = camera_stream[str(camera['id'])]
        for vehicle in detected_vehicles:
            vehicle_latitude, vehicle_longitude = vehicle['location'][1], vehicle['location'][0]
Exemple #12
0
# from keys import MAPS_API_KEY

# Change current working directory, only needed for Atom
os.chdir(os.path.dirname(os.path.abspath(__file__)))

today_date: str = date.today().strftime("%m-%d-%y")
report_path = f'../reports/all_time.xlsx'
report: openpyxl.workbook.Workbook = load_workbook(filename=report_path)
worksheet: openpyxl.worksheet.worksheet.Worksheet = report.active

MAPS_API_KEY = ''

googlemaps_client = googlemaps.Client(key=MAPS_API_KEY)

'''# 40.3, -75, 6 creates a default zoom over the entire state of Virginia '''
gmap_plotter_client = gmplot.GoogleMapPlotter(40.3, -75, 6)

gmap_plotter_client.apikey = MAPS_API_KEY

for cell in worksheet['H']:
    str_value = str(cell.value)
    str_value = str_value.replace('   ', '')
    if '|' in str_value:
        str_value = str_value[0: str_value.find('|')]
    geocode_result = googlemaps_client.geocode(str_value)[0]
    lat, lng = geocode_result['geometry']['location']['lat'], geocode_result['geometry']['location']['lng']
    print(str(lat) + str(lng))
    gmap_plotter_client.marker(lat, lng)

gmap_plotter_client.draw(f'../maps/{today_date}.html')
Exemple #13
0
    elif cols[-1] == "bits/sec":
        speed /= 1000
    np_idx = time - min(times)
    speeds[np_idx] = speed

shape_2d = (int(num / 15), 15)
num_2d = int(num / 15) * 15
lats = lats[:num_2d].reshape(shape_2d)
longs = longs[:num_2d].reshape(shape_2d)
speeds = speeds[:num_2d].reshape(shape_2d)
speeds = np.nanmean(speeds, axis=1)
lats = np.nanmean(lats, axis=1)
longs = np.nanmean(longs, axis=1)

gmap = gmplot.GoogleMapPlotter(np.nanmean(lats),
                               np.nanmean(longs),
                               12,
                               apikey=GMAP_API_KEY)
for i in range(len(lats) - 1):
    avg_speed = (speeds[i] + speeds[i + 1]) / 2
    color = ""
    if avg_speed >= 1000:
        color = "green"
    elif avg_speed < 1000 and avg_speed > 1:
        color = "orange"
    elif avg_speed <= 1:
        color = "red"
    else:
        color = "black"
    gmap.plot(lats[i:i + 2],
              longs[i:i + 2],
              color=color,
from gmplot import gmplot
import os

# Place map
gmap = gmplot.GoogleMapPlotter(49.839683, 24.029717, 13)


def readFile(path):
    """
    (str) -> list
    The function opens the file
    and get all data from it, storing
    it in the list
    """
    lst = []
    f = open(path, encoding="utf-8", errors="ignore")
    for i in f:
        lst.append(i)

    return lst


def putMarker(coord, color):
    """
    (tuple, str) -> Nonetype
    Using the abstract data type and
    google api, the function puts the marker
    on the map
    """
    gmap.marker(coord[0], coord[1], color=color)
Exemple #15
0
import folium
from gmplot import gmplot

df = pd.read_csv("data/yellow_tripdata_2017-01.csv")

location_df = pd.read_csv("v2_zone_geocode.csv")
location_df = location_df.drop(["Unnamed: 0"], axis=1)

#drop other column
# df['DOLocationID'].value_counts().reset_index().to_csv('destination_count.csv')

# merging two df

lat_lng_count_df = pd.merge(df,
                            location_df,
                            left_on='DOLocationID',
                            right_on="LocationID",
                            how='left')
print(lat_lng_count_df.shape[0])

# NYC
# random 300000 data - gmplot cannot handle
data = lat_lng_count_df.head(n=300000)
gmap = gmplot.GoogleMapPlotter(40.758896, -73.985130, 9)

# Overlay our datapoints onto the map
gmap.heatmap(data['lat'], data['lng'])
gmap.draw("heatmap.html")
#map = folium.Map(location=[40.758896, -73.985130], tiles="Stamen Terrain", zoom_start=13)
#map.add_children(plugins.HeatMap(stationArr, radius=15))
import pandas as pd
from gmplot import gmplot
import numpy as np

if __name__ == '__main__':
    places = pd.read_csv('data/places.csv')
    lat = places['Latitude']
    lon = places['Longitude']
    dates = places['Date']

    gmap = gmplot.GoogleMapPlotter(lat[0], lon[0], 5)
    gmap.heatmap(lat, lon, radius=10, maxIntensity=10)
    gmap.draw("my_map_heatmap.html")
Exemple #17
0
from gmplot import gmplot as gp
import csv
import random

map = gp.GoogleMapPlotter(40.1105875,
                          -88.2072697,
                          13,
                          apikey="AIzaSyCLV6iOyD6d60RXPgpzMf4baAy8ZqjCdYE")

path = "trips_data.csv"

path_corider = "trips_data_Xiaolu.csv"
data = []

with open(path) as file:
    reader = csv.reader(file)
    headers = next(reader)

    for row in reader:
        if len(row[5]) != 0:
            lat = (float(row[5]), float(row[9]))
            lng = (float(row[6]), float(row[10]))
            data.append((lat, lng))

for pair in data:
    r = lambda: random.randint(0, 255)
    color = '#%02X%02X%02X' % (r(), r(), r())
    map.plot(pair[0], pair[1], color, edge_width=3)

# draw
start_points = []
    locationInfo("Beijing", "textfile/Beijing.txt"),
    locationInfo("Seoul", "textfile/Seoul.txt")
]

# search for coordinate using geopy

print("Location - (Latitude, Longitude)")
geolocator = Nominatim(user_agent="Ben")
for x in range(len(locationList)):
    location = geolocator.geocode(locationList[x].name)
    locationList[x].setAddress(location.address)
    locationList[x].setCoor(location.latitude, location.longitude)
    locationList[x].print_location_information()

    # marking location using gmplot
gmap = gmplot.GoogleMapPlotter(locationList[4].latitude,
                               locationList[4].longitude, 3)

# 2. Placing/Mark all points(drop markers)
for x in range(len(locationList)):
    gmap.marker(locationList[x].latitude, locationList[x].longitude)
print("")

# 3. Get Distance
print("The distance of the city(3 decimal place):")
print("%15s|" % (''), end='')
for i in range(len(locationList)):
    print("%15s|" % (locationList[i].name), end='')
print('')
distanceCountry = [[0] * len(locationList) for i in range(len(locationList))]
for i in range(len(locationList)):
    print("%-15s|" % locationList[i].name, end='')
Exemple #19
0
# lat = min(lat1, lat2)
# long = min(long1, long2)

num_patients = 294
num_clinics = 30
# todo: search if there's 2d random generating coordinates
patients_latitude = np.random.uniform(br[0], tl[0], num_patients)
# print(patients_latitude)
patients_longtitude = np.random.uniform(bl[1], tr[1], num_patients)
# print(patients_longtitude)
patients_coord = zip(patients_latitude, patients_longtitude)
# for tup in patients_coord:
#     print(tup)
clinics_latitude = np.random.uniform(br[0], tl[0], num_clinics)
# print(patients_latitude)
clinics_longtitude = np.random.uniform(bl[1], tr[1], num_clinics)

# berkshire_coord = (42.3118, 73.1822)
gmap = gmplot.GoogleMapPlotter(42.446, -73.192, 10.5)

gmap.heatmap(patients_latitude, patients_longtitude)

for x, y in zip(clinics_latitude, clinics_longtitude):
    gmap.marker(x, y, "darkred")

# todo: add outline on map

gmap.apikey = "AIzaSyDE_MLUeIdpPgnCWEV-ZgscLCO1734Ax3w"

gmap.draw("my_map.html")
def visualize(filename, dataset_name, lat_name, lon_name, spatial_resolution,
              standard_deviations, map_name):
    dataset = netCDF4.Dataset(filename, "r")

    gmap = gmplot.GoogleMapPlotter(
        (dataset.variables[lat_name][0] + dataset.variables[lat_name][-1]) / 2,
        (dataset.variables[lon_name][0] + dataset.variables[lon_name][-1]) / 2,
        3)

    standard_deviation = np.std(np.array(dataset.variables[dataset_name]))
    average = np.average(np.array(dataset.variables[dataset_name]))
    increment = 0
    maximum = 0
    datapoints = []
    percentage = -1
    print("[-] Extracting data...")
    for lat in range(len(dataset.variables[dataset_name][0])):
        for lon in range(len(dataset.variables[dataset_name][0][lat])):
            if dataset.variables[dataset_name][0][lat][
                    lon] > standard_deviation * standard_deviations + average or dataset.variables[
                        dataset_name][0][lat][lon] < 1:
                continue
            else:
                datapoints.append([])
                datapoints[increment].append(lat)
                datapoints[increment].append(lon)
                if dataset.variables[dataset_name][0][lat][lon] > maximum:
                    maximum = dataset.variables[dataset_name][0][lat][lon]
                increment += 1
        if exact_round(lat / (len(dataset.variables[lat_name]) - 1) *
                       100) != percentage:
            percentage = exact_round(
                lat / (len(dataset.variables[lat_name]) - 1) * 100)
            os.system("cls" if os.name == "nt" else "clear")
            if percentage != 100:
                print("\t" + str(percentage) + "%\t [" + "=" * percentage +
                      ">" + " " * (100 - percentage) + "]")
            else:
                print("\t100% [" + "=" * 100 + ">]")
    print("[+] Data extraction finished.")
    print("[-] Plotting data...")
    percentage = -1
    for i in range(len(datapoints)):
        if rgb(
                scale_max(
                    dataset.variables[dataset_name][0][datapoints[i][0]][
                        datapoints[i][1]], maximum)) != [0, 0, 0]:
            gmap.scatter(
                [dataset.variables[lat_name][datapoints[i][0]]],
                [dataset.variables[lon_name][datapoints[i][1]]],
                "#" + hex_color(
                    rgb(
                        scale_max(
                            dataset.variables[dataset_name][0]
                            [datapoints[i][0]][datapoints[i][1]], maximum))),
                size=sum(spatial_resolution) * 15000,
                marker=False)
        if exact_round(i / (len(datapoints) - 1) * 100) != percentage:
            percentage = exact_round(i / (len(datapoints) - 1) * 100)
            os.system("cls" if os.name == "nt" else "clear")
            if percentage != 100:
                print("\t" + str(percentage) + "%\t [" + "=" * percentage +
                      ">" + " " * (100 - percentage) + "]")
            else:
                print("\t100% [" + "=" * 100 + ">]")
    print("[+] Data plotting finished.")
    print("[-] Rendering map...")
    gmap.draw(map_name)
    print("[+] Map rendering finished.")
    os.system(map_name)
    return map_name
Exemple #21
0
        path_run = os.path.join(path, run_name)
        if not os.path.exists('/home/jacob/DNDO/IMU_GPS/' + name):
            string = 'mkdir /home/jacob/DNDO/IMU_GPS/' + name
            os.system(string)
        pd_gps = pandas.read_csv(os.path.join(path_run, 'vectornav_gps.csv'))
        pd_ins = pandas.read_csv(os.path.join(path_run, 'vectornav_ins.csv'))
        pd_imu = pandas.read_csv(os.path.join(path_run, 'vectornav_imu.csv'))
        ins_time = [
            i - pd_ins['timestamp_unix'][0] for i in pd_ins['timestamp_unix']
        ]
        gps_time = [
            i - pd_ins['timestamp_unix'][0] for i in pd_gps['timestamp_unix']
        ]

    if plot:
        gmap = gmplot.GoogleMapPlotter(pd_ins['Latitude'][0],
                                       pd_ins['Longitude'][0], 18)
        gmap.plot(pd_ins['Latitude'],
                  pd_ins['Longitude'],
                  colors['ins'],
                  edge_width=7)
        gmap.plot(pd_gps['Latitude'],
                  pd_gps['Longitude'],
                  colors['gps'],
                  edge_width=7)
        gmap.scatter([pd_ins['Latitude'][0]], [pd_ins['Longitude'][0]],
                     'green')
        gmap.scatter([pd_ins['Latitude'].iloc[-1]],
                     [pd_ins['Longitude'].iloc[-1]], 'red')
        gmap.scatter([pd_gps['Latitude'][0]], [pd_gps['Longitude'][0]],
                     'green')
        gmap.scatter([pd_gps['Latitude'].iloc[-1]],
import plotly
from gmplot import gmplot
import os
import pandas as pd

cwd = os.getcwd()
dataSet = pd.read_csv(cwd + "/Data/sfpd_dispatch_data_subset.csv")
gmapFrequency = gmplot.GoogleMapPlotter(37.762289, -122.445359, 13)
gmapFrequency.heatmap(dataSet['latitude'], dataSet['longitude'])
gmapFrequency.draw("frequency.html")

gmapNotUrgent = gmplot.GoogleMapPlotter(37.762289, -122.445359, 13)
gmapUrgent = gmplot.GoogleMapPlotter(37.762289, -122.445359, 13)
notUrgentCoords = list()
urgentCoords = list()
for i in range(len(dataSet['received_timestamp'])):
    if dataSet['final_priority'][i] == 2:
        notUrgentCoords.append(
            (dataSet['latitude'][i], dataSet['longitude'][i]))
    elif dataSet['final_priority'][i] == 3:
        urgentCoords.append((dataSet['latitude'][i], dataSet['longitude'][i]))

#Gets the latitudes and longitudes into separate lists instead of in tuples
notUrgentlats, notUrgentlongs = zip(*notUrgentCoords)
urgentLats, urgentLongs = zip(*urgentCoords)

gmapNotUrgent.heatmap(notUrgentlats, notUrgentlongs)
gmapNotUrgent.draw("notUrgent.html")
gmapUrgent.heatmap(urgentLats, urgentLongs)
gmapUrgent.draw("urgent.html")
Exemple #23
0
from gmplot import gmplot
import json

# Place map
gmap = gmplot.GoogleMapPlotter(37.766956, -122.438481, 6)


with open('Location History.json') as json_data:
    d = json.load(json_data)
    lat_long = []
    for location in d["locations"]:
        lat_calc = (int(location["latitudeE7"] / 10000) * 10000) / 1e7
        long_calc = (int(location["longitudeE7"] / 10000) * 10000) / 1e7
        lat_long.append((lat_calc, long_calc))
    print(len(lat_long))
    set_lat_long = set(lat_long)
    print(len(set_lat_long))

#
# # Polygon
# golden_gate_park_lats, golden_gate_park_lons = zip(*lat_long)
# gmap.plot(golden_gate_park_lats, golden_gate_park_lons, 'cornflowerblue', edge_width=3)

# Scatter points
top_attraction_lats, top_attraction_lons = zip(*set_lat_long)
gmap.scatter(top_attraction_lats, top_attraction_lons, 'cornflowerblue', edge_width=4, marker=False)
#gmap.heatmap(top_attraction_lats, top_attraction_lons)

# Draw
gmap.draw("my_map.html")
Exemple #24
0
   ,'darkmagenta'
   , 'yellow'
   , 'navy'
   ,'darkorange'
   
   ,'purple'
   , 'orchid'
   ,'darkgray'
   ,'gold'
   ,'pink'

   
   
]

gmap = gmplot.GoogleMapPlotter(-68.779056, 33.529694,3 )
clustermat=[]
for i in range(1,max(list_labels)+1):
    clustermat.insert(i,[i])
for i in range(0,len(list_labels)):
    
    clustermat[list_labels[i]-1].append([datamovlatactual[i][0],datamovlatactual[i][1],datamovspd[i][0],datamovspd[i][1]])

for i in range(len(list_labels)):
    lats, lons = zip(datamovlatactual[i])
    
    gmap.scatter(lats, lons, color_codes[list_labels[i]], size=15600, marker=False)
gmap.draw("hack_dbscan_plot.html")  
gv=[]
for i in range(max(list_labels)):
    clustermat[i].pop(0)
    locationInfo("Bangkok"),
    locationInfo("Taipei"),
    locationInfo("Hong Kong"),
    locationInfo("Tokyo"),
    locationInfo("Beijing"),
    locationInfo("Seoul")
]

# search for coordinate using geopy
geolocator = Nominatim(user_agent="MyGeopy")
for x in range(len(locationList)):
    location = geolocator.geocode(locationList[x].name)
    locationList[x].setAddress(location.address)
    locationList[x].setLongitude(location.longitude)
    locationList[x].setLatitude(location.latitude)
    locationList[x].print_location_information()

# marking location using gmplot
# 1. Placing map(centered at KL)
gmap = gmplot.GoogleMapPlotter(locationList[0].latitude,
                               locationList[0].longitude, 13)

# 2. Placing all points(drop markers)
for x in range(len(locationList)):
    gmap.marker(locationList[x].latitude, locationList[x].longitude)

# 3.draw the map
gmap.draw("mapOflocation.html")

#Getting distance between cities
Exemple #26
0
from gmplot import gmplot

# Place map
gmap = gmplot.GoogleMapPlotter(77.8946302, 29.8622079, 8)

# # Polygon
# golden_gate_park_lats, golden_gate_park_lons = zip(*[
#     (37.771269, -122.511015),
#     (37.773495, -122.464830),
#     (37.774797, -122.454538)
#     ])
# gmap.plot(golden_gate_park_lats, golden_gate_park_lons, 'cornflowerblue', edge_width=10)

# # Scatter points
# top_attraction_lats, top_attraction_lons = zip(*[
#     (37.769901, -122.498331),
#     (37.768645, -122.475328),
#     (37.771478, -122.468677),
#     (37.769867, -122.466102),
#     (37.767187, -122.467496),
#     (37.770104, -122.470436)
#     ])
# gmap.scatter(top_attraction_lats, top_attraction_lons, '#3B0B39', size=40, marker=False)

# # Marker
# hidden_gem_lat, hidden_gem_lon = 37.770776, -122.461689
# gmap.marker(hidden_gem_lat, hidden_gem_lon, '#3B0B39')

# Draw
gmap.draw("my_map.html")
    #%% Determining how much a ships lat and long will move relative to speed
    foo = features[np.where(100012.0 == labels)[0], :]
    deltaTime = np.zeros(foo.shape[0] - 1)
    deltaPos = np.zeros((foo.shape[0] - 1, 2))
    for i in range(foo.shape[0] - 1):
        deltaTime[i] = foo[i + 1, 0] - foo[i, 0]
        deltaPos[i, 0] = foo[i + 1, 1] - foo[i, 1]  # latitude
        deltaPos[i, 1] = foo[i + 1, 2] - foo[i, 2]  #longitude
    print(np.sum(deltaTime) / np.shape(deltaTime))
    print("longitude = x, latitude = y")
    #%%
    from gmplot import gmplot
    uniq = np.array(np.unique(labels), dtype=int)
    z = np.array([['#000000'], ['#0000CD'], ['#0000FF'], ['#00BFFF'],
                  ['#00CED1'], ['#00FA9A'], ['#00FF00'], ['#00FF7F']])
    gmap = gmplot.GoogleMapPlotter(36.931199, -76.113555, 13,
                                   'get your own google API key')
    lat3, long3 = zip(*[(features3[:, 1], features3[:, 2])])
    gmap.scatter(lat3[0], long3[0], size=30, marker=False)
    gmap.draw("F:\Python File Saves\html's\lastSet.html")
    x, y = zip(*[(np.append(features[:, 1], features2[:, 1]),
                  np.append(features[:, 2], features2[:, 2]))])
    gmap.scatter(x[0], y[0], z[0], size=30, marker=False)
    gmap.draw("F:\Python File Saves\html's\scatter.html")
    gmap.heatmap(x[0], y[0])
    gmap.draw("F:\Python File Saves\html's\heatmap.html")
    gmap.plot(x[0], y[0])
    gmap.draw("F:\Python File Saves\html's\plot.html")

    #%%
    from sklearn.cluster import DBSCAN
    import pandas as pd
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 14:19:19 2018

@author: surbhi
"""

from gmplot import gmplot

# Place map
gmap = gmplot.GoogleMapPlotter(26.8851417, 75.6504706, 10)
# Scatter points
top_attraction_lats, top_attraction_lons = zip(*[
    (26.9198857,75.8194477),#chaura rasta rd
    (26.9200347,75.8249383),#johri bazar
    (26.8504847,75.8001958),#malviya nagar
    (26.9079421,75.7980539),#ashok nagar
    (26.8466574,75.8073311),#girdhar marg
    (26.9370594,75.8370154),#govind nagar
    (26.8916497,75.7907282),#lalkothi
    (26.9241727,75.7926167),#sindhi camp
    (26.783114,75.8222804),#sitapura
    (26.9167676,75.8109164),#MI road
    (26.8997037,75.8005478),#rambagh
    (26.9555944,75.7685048),#vidyadhar nagar
    ])
gmap.scatter(top_attraction_lats, top_attraction_lons, '#f21804', size=100, marker=False)


# Draw and save file as top10
gmap.draw("top10_hot_ar.html")
Exemple #29
0
            print('Path not reachable')
            break
    path.insert(0,start)
    if shortest_distance[goal] != infinity:
        print('Shortest distance is ' + str(shortest_distance[goal]))
        print('And the path is ' + str(path))

print(dijkstra(graph, "KL Sentral", "Legoland"))

#TASK 4 : PLOTTING ROUTE

import gmaps
#import googlemaps
from gmplot import gmplot
#gmaps = googlemaps.Client(api_key)
gmap = gmplot.GoogleMapPlotter(2.64, 102.803, 7)

gmap.scatter(df1['Latitude'],df1['Longitude'], '#FFFFFF', size=100, marker=False)
gmap.draw('maptest.html')

lat = df1["Latitude"].tolist()
lng = df1["Longitude"].tolist()

route0_lat = [lat[0],lat[1],lat[2],lat[3]]
route0_lng = [lng[0],lng[1],lng[2],lng[3]]
gmap.plot(route0_lat, route0_lng, "white", edge_width = 3.0)

route1_lat = [lat[0],lat[9],lat[10],lat[7],lat[8],lat[3]]
route1_lng = [lng[0],lng[9],lng[10],lng[7],lng[8],lng[3]]
gmap.plot(route1_lat, route1_lng, "blue", edge_width = 3.0)
START_LNG = '78.5718'
DEST_LAT = '17.2403'
DEST_LNG = '78.4294'
VIA_LAT = '17.4033'
VIA_LNG = '78.4707'

MODES = ['car', 'pedestrian', 'truck']

URL = 'https://router.hereapi.com/v8/routes?transportMode=car&origin={},{}&destination={},{}&return=polyline&apikey={}'
URL = URL.format(START_LAT, START_LNG, DEST_LAT, DEST_LNG, API_KEY)

URL_VIA = 'https://router.hereapi.com/v8/routes?transportMode=car&origin={},{}&destination={},{}&via={},{}&return=polyline&apikey={}'
URL_VIA = URL_VIA.format(START_LAT, START_LNG, DEST_LAT, DEST_LNG, VIA_LAT,
                         VIA_LNG, API_KEY)

r = requests.get(URL)
print(r.json())
polyline = r.json()["routes"][0]["sections"][0]["polyline"]
coordinates_list = fp.decode(polyline)

lat_list, lng_list = zip(*coordinates_list)

HYD_LAT = "17.3850"
HYD_LNG = "78.4867"
gmap = gmplot.GoogleMapPlotter(HYD_LAT, HYD_LNG, 11)

gmap.marker(float(START_LAT), float(START_LNG))
gmap.marker(float(DEST_LAT), float(DEST_LNG))
gmap.plot(lat_list, lng_list, edge_width=10)
gmap.draw("my_map.html")