Пример #1
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

        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, 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)
Пример #2
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)
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
Пример #4
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
Пример #5
0
def make_the_base_map():
    # set constants
    main_path = 'data'
    global api_key
    api_key = open(main_path + '/config.py', 'r')
    api_key = api_key.read().replace('api_key = ',
            '').replace('“','').replace('”','')
    gmaps.configure(api_key=api_key) # Your Google API key

    # get information
    df = pd.read_csv(main_path + '/nyc_blk_map_with_vals_for_front_end_FILTERED.csv')
    with open(main_path + '/BoroughBoundaries.geojson') as f:
        geometry = json.load(f)
    global nbhd_map
    nbhd_map = gpd.read_file(main_path + '/nyc_nbhd_map.shp')

    # Control the display
    global new_york_coordinates
    new_york_coordinates = (40.75, -73.9)
    heatmap_gradient = [
        (250, 185, 123, 0),
        'yellow',
        (249, 127, 77, 1),
        'red',
    ]

    # define layers
    global geojson_layer
    global heatmap_layer
    geojson_layer = gmaps.geojson_layer(geometry, fill_color=(0,0,0,0), 
            fill_opacity=1, stroke_weight=0.5)
    heatmap_layer = gmaps.heatmap_layer(df[['latitude', 'longitude']], 
            weights=df['magnitude'], max_intensity=10, 
            point_radius=0.00075, opacity=1, gradient=heatmap_gradient,
            dissipating=False)
Пример #6
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)
Пример #7
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)
Пример #8
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
Пример #9
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 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
 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
Пример #12
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
Пример #13
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
Пример #14
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
Пример #15
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
Пример #16
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)
    def google_map(seld):
        from gmaps.datasets import load_dataset_as_df
        df_earth = load_dataset_as_df('earthquakes')
        # print(df_earth.head())

        locations = df_earth[['latitude', 'longitude']]
        weights = df_earth['magnitude']
        fig = gmaps.figure()
        fig.add_layer(gmaps.heatmap_layer(locations, weights=weights))
        embed_minimal_html('jordan_map.html', views=[fig])
        return fig
    def _render_map(self, initial_maxIntensity, initial_radius):
        # fig = gmaps.figure(map_type='HYBRID')
        # fig = gmaps.figure(map_type='ROADMAP')
        fig = gmaps.figure()
        locations = self._locations
        weights = self._probabilities
        self._heatmap = gmaps.heatmap_layer(
            locations,
            weights=weights,
            max_intensity=initial_maxIntensity,
            opacity=0.8,
            point_radius=initial_radius,
            dissipating=True,
        )
        fig.add_layer(self._heatmap)
        l_weights = len(weights)
        N1 = int(l_weights / 100)
        #         N1 = min(N1,20)
        #         N1 = int(l_weights/2)
        #         N1 = l_weights
        N1 = 1000
        N1 = min(N1, len(weights))

        indicesForMarkers = np.argsort(weights)[-N1:]

        weightsMarked = weights[indicesForMarkers]
        locationsMarked = locations[indicesForMarkers]

        textForMarked = [
            'proba: {}\nlat: {}\nlon: {}'.format(a, b[0], b[1])
            for a, b in zip(weightsMarked, locationsMarked)
        ]

        self._symbolLayer = gmaps.symbol_layer(
            locationsMarked,
            hover_text=textForMarked,
            info_box_content=textForMarked,
            # stroke_opacity=1, # does not do anything
            # fill_opacity=1, # does not do anything
            stroke_color="rgba(255, 0, 0, 0.0)",
            # workaround for not working opacity
            fill_color=
            "rgba(255, 0, 0, 0.0)",  # workaround for not working opacity
            scale=3)
        fig.add_layer(self._symbolLayer)

        # self._markerLayer = gmaps.marker_layer(locationsMarked,
        #                                        hover_text=textForMarked,
        #                                        info_box_content=textForMarked,
        #                                        )
        # fig.add_layer(self._markerLayer)

        return fig
Пример #19
0
def plot_price_heatmap(df):
    APIKEY = os.getenv('GMAPAPIKEY')
    gmaps.configure(api_key=APIKEY)
    fig = gmaps.figure()
    df['location'] = df.apply(lambda x: (x['latitude'], x['longitude']), axis=1)
    locations = df['location']
    weights = df['price'].values
    #locations = (df['latitude'], df['longitude'])
    heatmap_layer = gmaps.heatmap_layer(locations, weights=weights)
    heatmap_layer.max_intensity = 2000
    heatmap_layer.point_radius = 30
    fig.add_layer(heatmap_layer)
    fig.savefig('../visualizations/price_heatmap.png')
Пример #20
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})
Пример #21
0
 def _render_map(self):
     """ Render the initial map """
     fig = gmaps.figure()
     self.heatmap = gmaps.heatmap_layer(
         self._df[['latitude', 'longitude']],
         max_intensity = self.max_intensity,
         point_radius = self.point_radius
     )
     fig.add_layer(self.heatmap)
     self.heatmap.max_intensity = self.max_intensity
     self.heatmap.point_radius = self.point_radius
     self.fig = fig
     self.gradient = self.heatmap.gradient
     return fig
Пример #22
0
 def render_map(self, initial_date):
     fig = gmaps.figure(map_type='HYBRID',
                        layout={
                            'width': '1000px',
                            'height': '800px'
                        },
                        zoom_level=self.zoom,
                        center=self.center)
     relevant_ix = self.locations_for_date(initial_date)
     self.heatmap = gmaps.heatmap_layer(self.coordinates[relevant_ix],
                                        weights=self.weights[relevant_ix],
                                        max_intensity=20.0)
     fig.add_layer(self.heatmap)
     return fig
Пример #23
0
def map_tweets(tweets, keyword):
coords = []
for tweet in tweets:
    if keyword is in tweet["text"]:
        coords.append(tweet["geo"])
return coords

coords = map_tweets(tweets, "weed")

gmaps.configure(api_key="AIzaSyADv13vyns8lTpdjwoxMwYL3Q0k2Eqoyno")
locations = coord
fig = gmaps.figure()
fig.add_layer(gmaps.heatmap_layer(locations))
fig
Пример #24
0
def heatmap(api, csv_file, product_list):
    """Creates a heatmap with prices data from one petrol product
    """
    gmaps.configure(api_key=api)
    df = pd.read_csv('bonarea_gasolineras_prices.csv')
    normalized_price = (df[product_list] - df[product_list].min()) / (
        df[product_list].max() - df[product_list].min())
    spain_coordinates = (41.8, -0.041509)
    fig = gmaps.figure(center=spain_coordinates, zoom_level=7)
    heatmap_layer = gmaps.heatmap_layer(df[['latitude', 'longitude']],
                                        weights=normalized_price,
                                        max_intensity=0,
                                        point_radius=20.0)
    fig.add_layer(heatmap_layer)
    return fig
Пример #25
0
def heatmap_all():
    '''
    plot the heatmap of all citation place
    '''
    df = pd.read_csv('parking-citations-processed.csv',
                     usecols=['Latitude_WGS', 'Longitude_WGS'],
                     low_memory=True)
    locations = df[['Latitude_WGS', 'Longitude_WGS']]
    locations = locations.groupby(['Latitude_WGS', 'Longitude_WGS'])
    freq = df.groupby(['Latitude_WGS',
                       'Longitude_WGS']).size().reset_index(name='freq')
    locations = freq[['Latitude_WGS', 'Longitude_WGS']]
    fig = gmaps.figure(center=los_angeles_coordinates, zoom_level=11)
    fig.add_layer(gmaps.heatmap_layer(locations, weights=freq['freq']))
    fig.add_layer(gmaps.traffic_layer())
    return fig
Пример #26
0
def get_data_points_figure(data):
    gmaps.configure(api_key=get_api_key())
    figure_layout = {'height': '500px', 'margin': '0 auto 0 auto'}
    fig = gmaps.figure(map_type="ROADMAP",
                       zoom_level=2,
                       center=(30, 31),
                       layout=figure_layout)
    heatmap_layer = gmaps.heatmap_layer(data)
    heatmap_layer.max_intensity = 100
    heatmap_layer.point_radius = 1
    heatmap_layer.dissipating = False

    # ToDo: consider using gmaps.symbol_layer with small markers

    fig.add_layer(heatmap_layer)
    return fig
Пример #27
0
def drawHeatMap(location, weights, radius):
    # setting the data and parameters

    heatmap_layer = gmaps.heatmap_layer(location,
                                        weights=weights,
                                        dissipating=True)
    heatmap_layer.point_radius = radius
    # draw the heatmap into a figure
    fig = gmaps.figure(
        layout={
            'width': '900px',
            'height': '550px',
            'padding': '3px',
            'border': '1px solid black'
        })
    #fig = gmaps.figure(center = [center_lat,center_lng], zoom_level=zoom)
    fig.add_layer(heatmap_layer)
    return fig
Пример #28
0
def gmap_heat_map(loc_list, info):
    """
    Take in a list of tuples (latitude, longitude) heat map using gmap.
    gmap's API key need to be stored in api_keys.py in the same folder. Just put in a variable gmap_key = 'AI...'
    :param loc_list: List of tuples (latitude, longitude) to be plotted
    :type loc_list: list of tuples
    :param info: The string to be shown on the plot
    :type info: str
    """
    import api_keys
    assert len(loc_list) > 0, 'Location list cannot be empty!'
    gmaps.configure(api_key=api_keys.gmap_key)
    fig = gmaps.figure(map_type='HYBRID')
    fig.add_layer(gmaps.heatmap_layer(loc_list, opacity=0.8, point_radius=20))
    fig.add_layer(
        gmaps.symbol_layer([(10.8, -83.0)],
                           fill_color='red',
                           stroke_color='red',
                           info_box_content=info,
                           scale=1))
    return fig
Пример #29
0
def heatmaps():
    try:
        df['Location'].replace('', np.nan, inplace=True)
        df.dropna(subset=['Location', 'Full Location'], inplace=True)
    except:
        print("...")
    lat = df['Latitude'].values
    lon = df['Longitude'].values
    """
    gmap=gmplot.GoogleMapPlotter(54.02,-0.94,6.5)
    gmap.apikey = "AIzaSyAhzINZ3b25CuR5ldJOdouaQLRE8_lUD78"
    gmap.heatmap(lat,lon,threshold=30, radius=10, gradient=None, opacity=0.4, dissipating=True)


    gmap.draw( "heatmap.html" )
    """
    txt.config(state=NORMAL)
    txt.insert(INSERT, "\n Done! ")
    txt.insert(INSERT, "\n Maps exported as interactive HTML - heatmap.html ")

    txt.config(state=DISABLED)

    #GMAPS CODE TO OUTPUT
    gmaps.configure(api_key='AIzaSyAhzINZ3b25CuR5ldJOdouaQLRE8_lUD78')

    figure_layout = {
        'width': '1600px',
        'height': '900px',
        'border': '1px solid black',
        'padding': '1px'
    }

    fig = gmaps.figure(layout=figure_layout, map_type='TERRAIN')
    heatmap_layer = gmaps.heatmap_layer(df[['Latitude', 'Longitude']],
                                        max_intensity=8,
                                        point_radius=5.0)
    fig.add_layer(heatmap_layer)
    embed_minimal_html('heatmap.html', views=[fig])
Пример #30
0
def park():
    '''
    Annocate parking lots
    '''
    df = pd.read_csv('parking-citations-processed.csv',
                     usecols=['Latitude_WGS', 'Longitude_WGS'],
                     low_memory=True)
    dfmark = clean_data('City_Owned_Parking_Lots.csv')
    parking_locations = dfmark[['Y', 'X']].loc[:1e6]

    locationsh = df[['Latitude_WGS', 'Longitude_WGS']]
    locationsh = locationsh.groupby(['Latitude_WGS', 'Longitude_WGS'])
    freq1 = df.groupby(['Latitude_WGS',
                        'Longitude_WGS']).size().reset_index(name='freq')
    locationsh = freq1[['Latitude_WGS', 'Longitude_WGS']]

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

    markers = gmaps.marker_layer(parking_locations)
    fig.add_layer(markers)
    fig.add_layer(gmaps.heatmap_layer(locationsh, weights=freq1['freq']))
    # fig.add_layer(gmaps.traffic_layer())
    return (fig)
Пример #31
0
y = clf.predict(df)
print y


# ### Location based prices ###
# House prices don't only depend on the size of the house or amount of rooms, but are also really dependant on the location of said house. To get an idea how the position might impact my data I analyse the relationship between location and price in my dataset.

# In[ ]:

import gmaps
gmaps.configure(api_key="AIzaSyDPWAl8lcrK9q-tOkrl64sGkxDnbWz47Ko")

locations = df[["lat", "long"]]
prices = df["price"]

heatmap_layer = gmaps.heatmap_layer(locations, weights=prices)
heatmap_layer.max_intensity = 7200000
heatmap_layer.point_radius = 4

fig = gmaps.figure()
fig.add_layer(heatmap_layer)
fig


# This graph shows that there seems to be a real relationship between location and price. Especially in the center of Seattle the prices are much higher. There is also the town of Snoqualmie which is known for having a lot of highly educated inhabitants. That circumstance leads to the people of Snoqualmie having a substantially higher household income than the average. 
# 
# Therefore, the housing prices are also higher in this area. The same reasons for higher living costs can also be applied to Seattle, which is much more attractive to live in for wealthy people.

# ### Using Support Vector Machines ###
# Because of the higher dimensionality of the feature space SVM might be well suited for this problem. In the following implementation I try to use SVM to improve my predictions.
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