Example #1
0
def maps_view(request, pk):
    device_data = Data.objects.get(pk=pk)
    latfloat = float(device_data.latitude)
    longfloat = float(device_data.longitude)

    gmaps.configure(api_key='AIzaSyAH6Tx3JJQvAkt4Tbw3tBWiSO8bLFrN41w')
    new_york_coordinates = (latfloat, longfloat)
    gmaps.figure(center=new_york_coordinates, zoom_level=12)

    return render(request, 'mapsview.html')
Example #2
0
def fun(request):

	gmaps.configure(api_key = 'AIzaSyBcT_KzlYcyYf-171L7pR6ngBgZHYq24C4')
	dataset = gmaps.datasets.load_dataset_as_df('earthquakes')
	dataset.head()
	location = dataset[['latitude','longitude']]
	weight = dataset['magnitude']
	fig = gmaps.figure()
	fig.add_layer(gmaps.heatmap_layer(location,weights = weight))
	fig = gmaps.figure(map_type='ROADMAP')
	# 'ROADMAP', 'HYBRID', 'TERRAIN', 'SATELLITE'

	return render(request,'index.html',{'fig':fig})
Example #3
0
def route_explorer_from_file():
    global reff_fig
    global reff_drawing
    global reff_dropdown
    global reff_routes

    reff_routes = open('routes.ipts').read().splitlines()

    reff_dropdown = widgets.Dropdown(
        options=[''] + reff_routes,
        description='Route',
        disabled=False,
    )

    def route_changed(r):
        global reff_drawing
        if r.new != '':
            map_plot(list(map(int, r.new.split(','))), reff_drawing)
        else:
            reff_drawing.features = []

    reff_dropdown.observe(route_changed, 'value')

    reff_fig = gmaps.figure(center=(55.785822, 12.521520),
                            zoom_level=16,
                            layout={
                                'height': '800px',
                                'width': '800px'
                            })
    reff_drawing = gmaps.drawing_layer(show_controls=False)
    reff_fig.add_layer(reff_drawing)

    display(reff_dropdown)
    display(reff_fig)
Example #4
0
    def plot_base_map(self, place='switzerland'):
        '''
        Create base map of switzerland

        arguments:
        ----------
        none 

        return:
        -------
        fig - gmaps figure 
        '''
        figure_layout = {
            'width': '1600px',
            'height': '1100px',
            'border': '1px solid black',
            'padding': '1px'
        }

        if place == 'switzerland':
            center_coords = self._config['switzerland_ctr']
        else:
            center_coords = self._config['winterthur_ctr']

        gmaps.configure(api_key=self._config['api_key'])
        fig = gmaps.figure(layout=figure_layout,
                           center=center_coords,
                           zoom_level=9)

        return fig
Example #5
0
def print_city_districts(city, opacity=None):
    """
    It prints all the districts of a city by looking at its geojson file.

    Parameters
    ----------
    city : string
        Name of the city whose districts we want to display.
    opacity : float
        It defines the opacity of the district layers. It supports a value in
        the range of [0,1]

    Returns
    -------
    my_map : gmaps object
        This object will be used to plot the map and all activities locations
        in a Jupyter Notebook.
    """
    my_map = gmaps.figure()
    with open('geojson/{}.geojson'.format(city), 'r') as f:
        districts_geometry = json.load(f)
    my_map.add_layer(
        gmaps.geojson_layer(districts_geometry,
                            stroke_color='black',
                            fill_opacity=(opacity or co.LAYER_TRANSPARENCY)))
    return my_map
Example #6
0
def googleMaps(dataset):
    ownAPIKey= 'go_get_it_from_google_maps_api'
    gmaps.configure(api_key=ownAPIKey)
    
    # create the info box template
    info_box_template = """
    <dl>
    <dt>Name</dt><dd>{name}</dd>
    <dt>ID</dt><dd>{id}</dd>
    <dt>Score</dt><dd>{score}</dd>
    <dt>Location</dt><dd>{location}</dd>
    <dt>Availability (%)</dt><dd>{available}</dd>
    <dt>URL</dt><dd>{listing_url}</dd>
    </dl>
    """
    dataset.drop(columns=['description'], inplace=True) # drop description as it is too long
    
    gmap_dict= dataset.to_dict('records') # convert each row into a dictionary of the list
    
    gmap_locations =dataset['location'].to_list() # to show the markers on the map
    
    gmap_info = [info_box_template.format(**id) for id in gmap_dict] #map the gmap_dict with the info box template
    
    marker_layer = gmaps.marker_layer(gmap_locations, info_box_content=gmap_info) # create the markers to be shown on google map
    
    fig = gmaps.figure()
    fig.add_layer(marker_layer) # combine with the current map
    embed_minimal_html('map.html', views=[fig])
Example #7
0
def PlotMap():
    # Fucntion to create basemap
    global count
    global community

    gmaps.configure('AIzaSyBwEyjaABv6E1VJK3P_GKmMrvCIs8QEBJI')
    # =============================================================================
    #     m  = Basemap(projection='mill',llcrnrlon=min(count['lon']),llcrnrlat=min(count['lat']),urcrnrlat=max(count['lat']),urcrnrlon=max(count['lon']))
    #     m.drawstates()
    #     m.drawcoastlines()
    #     m.drawcounties()
    # =============================================================================

    #Plotting the data
    # =============================================================================
    #     lon=np.array(count['lon'])
    #     lat=np.array(count['lat'])
    #     data=np.array(count['english'])
    #     x,y = m(lon,lat)
    #     m.scatter(x,y,data)
    # =============================================================================
    # =============================================================================
    #     data = [(float(count.iloc[i]['lat']), float(count.iloc[i]['lon'])) for i in range(len(count))]
    #     print(data)
    #     gmaps.heatmap(data)
    # =============================================================================
    locations = count[['lat', 'lon']]
    weight = count['english']
    fig = gmaps.figure()
    fig.add_layer(gmaps.heatmap_layer(locations, weights=weight))
    embed_minimal_html('export.html', views=[fig])
    return fig
Example #8
0
def hl_street():
    '''
    highlight streets with the most parking citations on Google map
    '''
    df = pd.read_csv('parking-citations-processed.csv',
                     usecols=['Latitude_WGS', 'Longitude_WGS', 'Street Name'],
                     low_memory=True)
    freq = df.groupby([
        'Street Name'
    ]).size().reset_index(name='freq').sort_values(by=['freq'],
                                                   ascending=False)
    most_streetslist = list(freq['Street Name'])[0:20]
    freq = df.groupby([
        'Street Name', 'Latitude_WGS', 'Longitude_WGS'
    ]).size().reset_index(name='freq').sort_values(by=['freq'],
                                                   ascending=False)
    freq = freq.set_index('Street Name')
    most_streetpoint = freq.loc[most_streetslist]
    most_points = list(
        zip(list(most_streetpoint['Latitude_WGS']),
            list(most_streetpoint['Longitude_WGS'])))
    most_points = list(set(most_points))

    fig = gmaps.figure(center=los_angeles_coordinates, zoom_level=12)

    most = gmaps.symbol_layer(most_points[::20],
                              fill_color='blue',
                              stroke_color='blue',
                              scale=3,
                              stroke_opacity=0)
    fig.add_layer(most)
    # fig.add_layer(gmaps.traffic_layer())
    return (fig)
Example #9
0
def show_google_map(paths, API_key, region):

    lines = []
    for f in pbar()(paths.fragments):
        flines = []
        for l in f:
            line_coords = np.r_[list(l.coords.xy)].T
            for i in range(len(line_coords) - 1):
                flines.append(
                    gmaps.Line(start=tuple(line_coords[i][::-1]),
                               end=tuple(line_coords[i + 1][::-1])))
        lines.append(flines)
    lines = flatten(lines)
    print "found", len(lines), "line segments"

    markers = []

    for o, f in pbar()(zip(flatten(paths.resampled_orientations),
                           flatten(paths.resampled_fragments))):
        coords = np.r_[list(f.xy)].T
        markers.append([
            gmaps.Marker((coords[i][1], coords[i][0]),
                         info_box_content=str(o[i]))
            for i in range(len(coords))
        ])
    markers = flatten(markers)
    print "found", len(markers), "sampling locations"

    gmaps.configure(api_key=API_key)
    gmap_b = gmaps.Polygon([(i[1], i[0]) for i in region])
    fig = gmaps.figure(center=tuple(region.mean(axis=0)[::-1]), zoom_level=16)
    fig.add_layer(gmaps.drawing_layer(features=[gmap_b] + lines + markers))
    return fig
Example #10
0
    def get(self, request, format=None):
        """Get route for crime map."""
        gmaps.configure(api_key=os.environ.get('MAPS_API'))

        locations = []
        for each in Crimes.objects.all():
            temp = []
            temp.append(each.latitude)
            temp.append(each.longitude)
            locations.append(temp)

        try:
            heatmap_layer = gmaps.heatmap_layer(locations)
        except TraitError:
            heatmap_layer = gmaps.heatmap_layer(
                [[47.465568160532435, -122.50131030799446]])

        heatmap_layer.gradient = [(0, 0, 0, 0.7), (255, 105, 180, 0.4),
                                  (255, 0, 0, 0.8)]

        fig = gmaps.figure()

        fig.add_layer(heatmap_layer)
        embed_minimal_html('export.html', views=[fig])

        export = open('export.html').read()

        return Response(export)
Example #11
0
def make_heatmap(locations, weights=None):
    fig = gmaps.figure()
    heatmap_layer = gmaps.heatmap_layer(locations)
    heatmap_layer.max_intensity = 100
    heatmap_layer.point_radius = 8
    fig.add_layer(heatmap_layer)
    return fig
def heatmap(tweets_location):

    print("Info: Building heatmap...", end='')

    #Seattle 47.60° N, 122.33° W
    #Miami   25.76° N, 80.19° W

    Lon = np.arange(-71.21, -71, 0.0021) 
    Lat = np.arange(42.189, 42.427, 0.00238) 
    Crime_counts = np.zeros((100,100))

    longitude_values = [Lon,]*100 
    latitude_values = np.repeat(Lat,100) 
    Crime_counts.resize((10000,)) 
    heatmap_data = {'Counts': Crime_counts, 'latitude': latitude_values, 'longitude' : np.concatenate(longitude_values)} 
    df = pd.DataFrame(data=heatmap_data)
    locations = df[['latitude', 'longitude']] 
    weights = df['Counts'] 
    fig = gmaps.figure() 
    heatmap_layer = gmaps.heatmap_layer(locations, weights=weights) 
    fig.add_layer(gmaps.heatmap_layer(locations, weights=weights))
    print(fig) 

    print("DONE!")

    return 0
Example #13
0
def drawMarkerOnMap(df):
    df_ = __getDfWithLoaction(df)
    popUpList = __makePopUpList(df_)
    post_locations = [post['location'] for post in popUpList]

    info_box_template = """
    <dl>
    <dt>User</dt><dd>{owner_name}</dd>
    <dt>Is_Video</dt><dd>{is_video}</dd>
    <dt>Likes</dt><dd>{likes}</dd>
    <dt>Time</dt><dd>{time}</dd>
    <dt>Location Name</dt><dd>{loc_name}</dd>
    <dt>Comment Count</dt><dd>{comment_cnt}</dd>
    <dt>View</dt><dd>{video_view_count}</dd>
    <dt>Tags</dt><dd>{tags}</dd>
    </dl>
    """
    post_info = [info_box_template.format(**post) for post in popUpList]
    marker_layer = gmaps.marker_layer(post_locations,
                                      info_box_content=post_info)
    fig = gmaps.figure(center=(37.532600, 127.024612), zoom_level=10)
    fig.add_layer(marker_layer)

    print(len(post_info))
    return fig
Example #14
0
    def get(self, request, format=None):
        """Get route for entertainment map."""
        gmaps.configure(api_key=os.environ.get('MAPS_API'))

        locations = []
        for each in Entertainment.objects.all():
            temp = []
            p = re.compile('[()°,]')  # I know this is bad regex
            split_location = p.sub('', str(each.location)).split()
            try:
                if split_location[0] != 'None' or split_location[1] != 'None':
                    temp.append(float(split_location[0]))
                    temp.append(float(split_location[1]))
                    locations.append(temp)
            except IndexError:
                pass

        heatmap_layer = gmaps.heatmap_layer(locations)

        heatmap_layer.gradient = [(0, 0, 0, 0.7), (255, 178, 102, 0.4),
                                  (255, 128, 0, 0.8)]

        fig = gmaps.figure()

        fig.add_layer(heatmap_layer)
        embed_minimal_html('export.html', views=[fig])

        export = open('export.html').read()

        return Response(export)
Example #15
0
def markers_direction():
    figure_layout = {
        'width': '1600px',
        'height': '1100px',
        'border': '1px solid black',
        'padding': '1px'
    }

    switzerland_ctr_coord = config['switzerland_ctr']
    gmaps.configure(api_key=config['api_key'])
    fig = gmaps.figure(layout=figure_layout,
                       center=switzerland_ctr_coord,
                       zoom_level=9)

    winterthur_lat, winterthur_lon = map.city_lat_lon('Winterthur')
    zurich_lat, zurich_lon = map.city_lat_lon('Zurich')
    winterthur_point = map.city_point('Winterthur')
    zurich_point = map.city_point('Zurich')

    locations = [(winterthur_lat, winterthur_lon), (zurich_lat, zurich_lon)]
    fig = map.add_marker(fig, locations)
    fig = map.add_direction(fig,
                            winterthur_point,
                            zurich_point,
                            mode='DRIVING')
Example #16
0
def get_lat_lng(apiKey, address):  #2 farklı fonksiyon belirliyoruz.
    global output_address
    url = (
        'https://maps.googleapis.com/maps/api/geocode/json?address={}&key={}'.
        format(address.replace(' ', '+'), apiKey)
    )  #Sonucu bir yere getirmek için json formatında bir url kullanıyoruz.
    try:
        response = requests.get(
            url
        )  #url deki değerleri en baştaki requests kütüphanesi sayesinde sorguluyoruz./#We query values ​​in url with the requests library at the very beginning.
        resp_json_payload = response.json(
        )  #Hatırlarsanız URL miz json formatındaydı.önceki koddaki sorgudan çekdiğimiz değeri json olarak ayarlıyoruz. #If you remember, our URL was in json format. We set the value we got from the query in the previous code to json.
        output_address = resp_json_payload["results"][0]["formatted_address"]
        lat = resp_json_payload['results'][0]['geometry']['location'][
            'lat']  #Burda lokasyonumuzun geometrik değerlerini lat türünden alıyoruz.
        lng = resp_json_payload['results'][0]['geometry']['location'][
            'lng']  #Burda lokasyonumuzun geometrik değerlerini lng türünden alıyoruz.
        gmaps.configure(api_key=apiKey)
        location = (lat, lng
                    )  #lat ve lng değerlerini lokasyon değerine aktarıyoruz.
        fig = gmaps.figure(
            center=location, zoom_level=15
        )  #orta merkezi lokasyon olarak seçiyoruz ve yakınlaştırmayı 15 yapıyoruz ki daha dinamik olsun.

    except:  #Bir hatamız olursa diye bir dönüt yazıyoruz.
        print('HATA: Lokasyon bulunamadı.'.format(address))
        lat = 0
        lng = 0
    return lat, lng, output_address, fig
Example #17
0
    def get(self, request, format=None):
        """Get route for Dirtiness map."""
        gmaps.configure(api_key=os.environ.get('MAPS_API'))

        locations = []
        for each in Dirtiness.objects.all():
            temp = []
            if each.latitude and each.longitude:
                temp.append(each.latitude)
                temp.append(each.longitude)
                locations.append(temp)

        heatmap_layer = gmaps.heatmap_layer(locations)

        heatmap_layer.gradient = [(0, 0, 0, 0.7), (255, 178, 102, 0.4),
                                  (102, 51, 0, 0.8)]

        fig = gmaps.figure()

        fig.add_layer(heatmap_layer)
        embed_minimal_html('export.html', views=[fig])

        export = open('export.html').read()

        return Response(export)
Example #18
0
def heatmap_plot(hotels):
    """
    Generates a heatmap of the ideal cities

    Parameters
    ----------
    ideal_cities : TYPE: DataFrame
        DESCRIPTION. : ideal cities subset of entire cities sample based 
                        on the humidity

    Returns
    -------
    None.

    """

    print("generating heatmap plots hotels")
    hotel_locations = [(hotel["lat"], hotel["lng"]) for hotel in hotels]

    motel_info = [hotel["name"] for hotel in hotels]

    heat_layer = gmaps.heatmap_layer(hotel_locations,
                                     dissipating=False,
                                     max_intensity=100,
                                     point_radius=5)

    # marker_layer = gmaps.marker_layer(motel_locations,
    #                              info_box_content=motel_info)
    fig = gmaps.figure()
    fig.add_layer(heat_layer)
    # fig.add_layer(marker_layer)

    print("generation complete")
    show(block=False)
 def _render_map(self, initial_include_starbucks, initial_include_kfc):
     """ Render the initial map """
     fig = gmaps.figure(layout={'height': '500px'})
     symbols = self._generate_symbols(True, True)
     self._symbol_layer = gmaps.Markers(markers=symbols)
     fig.add_layer(self._symbol_layer)
     return fig
Example #20
0
def showfig(datasets, weights, weekday):
    '''
    '''
    assert weekday in range(7)
    fig = gmaps.figure(center=(34.0522, -118.2437), zoom_level=11)
    fig.add_layer(
        gmaps.heatmap_layer(datasets[weekday], weights=weights[weekday]))
    return fig
Example #21
0
def gen_heat_map(x, name):
    locations = np.stack((x[:, 0], x[:, 1]), axis=-1)
    weights = x[:, 2]
    fig = gmaps.figure()

    fig.add_layer(gmaps.heatmap_layer(locations, weights=weights))

    embed_minimal_html('export_{}.html'.format(name), views=[fig])
 def _render_map(self, initial_year):
     fig = gmaps.figure(map_type='HYBRID')
     self._heatmap = gmaps.heatmap_layer(
         self._locations_for_year(initial_year),
         max_intensity=100,
         point_radius=8)
     fig.add_layer(self._heatmap)
     return fig
def drawHeatMap(location, val, zoom, intensity, radius):
    heatmap_layer = gmaps.heatmap_layer(locations, val, dissipating = True)
    heatmap_layer.max_intensity = intensity
    heatmap_layer.point_radius = radius
    
    fig = gmaps.figure(map_type='HYBRID')
    fig.add_layer(heatmap_layer)
    return fig
Example #24
0
def plotData(distanceData, radius=0.005):
    valid = []
    for trip in distanceData:
        if trip[-1] <= radius and trip[-2] <= radius:
            valid.append([trip[2], trip[3]])
    valid = np.array(valid)
    fig = gmaps.figure()
    fig.add_layer(gmaps.heatmap_layer(valid))
    return fig
Example #25
0
 def __init__(self, datasets, weights):
     self._datasets = datasets
     self._weights = weights
     self._figure = gmaps.figure(center=(34.0522, -118.2437), zoom_level=11)
     self._current_index = 0
     self._heatmap = gmaps.heatmap_layer(
         datasets[self._current_index],
         weights=weights[self._current_index])
     self._figure.add_layer(self._heatmap)
Example #26
0
def create_map(pairs, key):
    new_york_coordinates = (40.75, -74.00)
    gmaps.configure(api_key=key)
    fig = gmaps.figure(center=new_york_coordinates, zoom_level=11)
    heatmap_layer = gmaps.heatmap_layer(pairs)
    heatmap_layer.max_intensity = 1
    heatmap_layer.point_radius = 15
    fig.add_layer(heatmap_layer)
    return fig
Example #27
0
def myfunpro(po):             #argument:dataframe(df)
    lat_list = list(po["latitude"])
    long_list = list(po["longitude"])
    gmaps.configure(api_key="AIzaSyDmXhcX8z4d4GxPxIiklwNvtqxcjZoWsWU")
    fig = gmaps.figure()
    var1 = json.dumps(
        [{'lat': country, 'lng': wins} for country, wins in zip(lat_list, long_list)]
    )
    return var1
Example #28
0
def draw(dataframe):

    locations = dataframe[["latitude", "longitude"]]
    weights = dataframe["i alt"]

    fig = gmaps.figure()
    fig.add_layer(gmaps.heatmap_layer(locations, weights=weights))

    return fig
Example #29
0
def geneva2zurich():

    geneva = (46.2, 6.1)
    montreux = (46.4, 6.9)
    zurich = (47.4, 8.5)
    fig = gmaps.figure()
    geneva2zurich = gmaps.directions_layer(geneva, zurich)

    return geneva, zurich, geneva2zurich
Example #30
0
def get_traffic_html():
    gmaps.configure(api_key=config.google_config['API_key'])

    # Map centered on London
    fig = gmaps.figure(center=(51.5, -0.2), zoom_level=11)
    # fig.add_layer(gmaps.bicycling_layer())
    fig.add_layer(gmaps.traffic_layer())
    print(help(fig))
    # embed_minimal_html('export.html', views=[fig])
    return None
import gmaps
import gmaps.datasets
gmaps.configure(api_key="AI...")  # Your Google API key

locations = gmaps.datasets.load_dataset("taxi_rides")

fig = gmaps.figure()

# locations could be an array, a dataframe or just a Python iterable
fig.add_layer(gmaps.heatmap_layer(locations))

fig