Exemplo n.º 1
0
def generate_segements_sim(config, session, Segments, Routes, segment_ids,
                           route_ids, matrix):
    map_options = config['map_options']
    ref_routes = np.unique(route_ids)
    ref_files = {
        i: session.query(Routes.path).filter(Routes.id == int(i)).first().path
        for i in ref_routes
    }

    if config['apply']['aggregation'].lower().strip() == 'mean':
        aggregation_func = np.mean
    elif config['apply']['aggregation'].lower().strip() == 'median':
        aggregation_func = np.median
    elif config['apply']['aggregation'].lower().startswith('trim_mean'):
        _, _, percentage = config['apply']['aggregation'].partition('::')
        aggregation_func = functools.partial(trim_mean,
                                             proportiontocut=float(percentage))
    else:
        raise ValueError(
            f"{config['apply']['aggregation']} is not a valid aggregation function!"
        )
    mean_dist = np.empty(len(ref_routes), dtype=float)
    for i, idx_i in enumerate(ref_routes):
        mask_i = route_ids == idx_i
        dist_ij = matrix[:, mask_i]
        min_dist = np.min(dist_ij, axis=1)
        mean_dist[i] = aggregation_func(min_dist)

    mean_dist[mean_dist < 0.006] = np.inf
    idx_min = np.argmin(mean_dist)
    path_most_sim = ref_files[ref_routes[idx_min]]
    route_entry = session.query(Routes).filter(
        Routes.path == path_most_sim).first()
    route_mask = route_ids == ref_routes[idx_min]
    matrix_sim = matrix[:, route_mask]
    segments = []
    for idx in segment_ids[route_mask]:
        segment = session.query(Segments).filter(
            Segments.id == int(idx)).first()
        mm = geotiler.Map(extent=(segment.p_0_long, segment.p_0_lat,
                                  segment.p_1_long, segment.p_1_lat),
                          zoom=map_options['zoom'])
        mm = geotiler.Map(center=mm.center,
                          zoom=map_options['zoom'],
                          size=(map_options['width'], map_options['width']))
        segments.append({
            'point':
            GPXTrackPoint(latitude=mm.center[1], longitude=mm.center[0]),
            'origin':
            route_entry.path
        })
    return segments, matrix_sim, route_entry.gpx_file
Exemplo n.º 2
0
def generate_img_sim_global(config, session, Segments, matrix, segment_ids,
                            embedding_model, render_map):
    map_options = config['map_options']
    idx = np.argmin(matrix, axis=1)
    min_values = np.min(matrix, axis=1)
    segment_idx = segment_ids[idx]
    segments = []
    images = []
    entries = []
    batch_size = config.get('apply').get('batch_size', 16)
    for (idx, value) in zip(segment_idx, min_values):
        entry = session.query(Segments).filter(Segments.id == int(idx)).first()
        entry = row2dict(entry)
        mm = geotiler.Map(extent=(entry['p_0_long'], entry['p_0_lat'],
                                  entry['p_1_long'], entry['p_1_lat']),
                          zoom=map_options['zoom'])
        mm = geotiler.Map(center=mm.center,
                          zoom=map_options['zoom'],
                          size=(map_options['width'], map_options['width']))
        entry['point'] = GPXTrackPoint(latitude=mm.center[1],
                                       longitude=mm.center[0])
        entry['image_raw'] = render_map(mm).convert('RGB')
        entry['image_encoded'] = tf.reshape(
            tf.convert_to_tensor(bytes2array(entry['image']),
                                 dtype=tf.float32),
            map_options['encoding_shape'])
        entry[
            'image_for_reconstruction'] = tf.keras.preprocessing.image.img_to_array(
                entry['image_raw']) / 255.
        entry['dist'] = value
        del entry['image']
        entries.append(entry)
        images.append(entry['image_for_reconstruction'])
        if len(images) == batch_size:
            reconstructed_images, *_ = apply_model(embedding_model,
                                                   images,
                                                   batch_size,
                                                   fill_up=False)
            for img_decoded, entry in zip(reconstructed_images, entries):
                entry['image_decoded'] = img_decoded.numpy()
                segments.append(entry)
            images, entries = [], []
    if len(entries) > 0:
        reconstructed_images, *_ = apply_model(embedding_model,
                                               images,
                                               batch_size,
                                               fill_up=True)
        for img_decoded, entry in zip(reconstructed_images, entries):
            entry['image_decoded'] = img_decoded.numpy()
            segments.append(entry)
    return segments
Exemplo n.º 3
0
def saveMap(loc, name):
    minlat = np.min(loc["lat"]) - .05
    minlon = np.min(loc["lon"]) - .05
    maxlat = np.max(loc["lat"]) + .05
    maxlon = np.max(loc["lon"]) + .05

    gtm = geotiler.Map(extent=(minlon, minlat, maxlon, maxlat),
                       zoom=11,
                       provider="stamen-terrain")
    image = geotiler.render_map(gtm)
    w, h = image.size

    fig = plt.figure(frameon=False)
    fig.set_size_inches(w / 500, h / 500)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    bm = Basemap(llcrnrlon=minlon,
                 llcrnrlat=minlat,
                 urcrnrlon=maxlon,
                 urcrnrlat=maxlat,
                 lat_0=(minlat + maxlat) / 2,
                 lon_0=(minlon + maxlon) / 2,
                 projection="tmerc",
                 resolution=None)
    bm.imshow(image, aspect='equal', origin='upper')
    bm.plot(loc["lon"], loc["lat"], linewidth=1, color='r', latlon=True)
    bm.plot(loc["lon"][0], loc["lat"][0], 'go', latlon=True)
    fig.savefig(name, dpi=500)
Exemplo n.º 4
0
def plot_gps_data(ax, *args, zoom=11, margin=0.1):
    import geotiler
    import numpy as np

    if len(args) == 1:
        df = args[0]
        latitudes = df['latitude'].values
        longitudes = df['longitude'].values
    else:
        latitudes = args[0]
        longitudes = args[1]

    extent = [
        longitudes.min(),
        latitudes.min(),
        longitudes.max(),
        latitudes.max()
    ]

    region = geotiler.Map(extent=extent, zoom=zoom)
    w, h = region.size
    scale_factor = 1 + margin
    w = max(100, int(scale_factor * w))
    h = max(100, int(scale_factor * h))
    region.size = (w, h)
    img = geotiler.render_map(region)

    points = zip(longitudes, latitudes)
    x, y = zip(*(region.rev_geocode(p) for p in points))

    ax.imshow(img)
    ax.plot(x, y, c='blue')
    return ax, img
Exemplo n.º 5
0
def getMapPngFile(lat, lon, filename):
    lats = []
    lons = []
    # Small Scale
    fig = plt.figure(figsize=(5, 5))
    ax = plt.subplot(111)
    #
    # download background map using OpenStreetMap
    #
    mm = geotiler.Map(center=(lon, lat),
                      zoom=11,
                      size=(512, 512),
                      provider='stamen-toner')
    img = geotiler.render_map(mm)
    #
    # create basemap
    #
    bbox = mm.extent
    map = Basemap(llcrnrlon=bbox[0],
                  llcrnrlat=bbox[1],
                  urcrnrlon=bbox[2],
                  urcrnrlat=bbox[3],
                  projection='merc',
                  ax=ax)
    map.imshow(img, interpolation='lanczos', origin='upper')
    lats.append(lat)
    lons.append(lon)
    x, y = map(lons, lats)
    map.scatter(x, y, 125, marker='o', color='r')
    plt.savefig(filename, bbox_inches='tight')
    plt.close()
Exemplo n.º 6
0
def random_coords_no_ocean() -> Coordinates:

    WATER_COLOR = [223, 211, 170]

    asyncio.set_event_loop(asyncio.new_event_loop())
    resized: np.ndarray
    coords: Coordinates
    while True:
        coords = random_coords()
        map = geotiler.Map(center=(coords.lng, coords.lat),
                           zoom=9,
                           size=(1200, 800))
        image = geotiler.render_map(map).convert('RGB')
        open_cv_image = numpy.array(image)
        img = open_cv_image[:, :, ::-1].copy()

        scale_percent = 5  # percent of original size
        width = int(img.shape[1] * scale_percent / 100)
        height = int(img.shape[0] * scale_percent / 100)
        dim = (width, height)
        resized = cv.resize(img, dim, interpolation=cv.INTER_AREA)

        count = countPixelsInRange(resized, [x - 5 for x in WATER_COLOR],
                                   [x + 5 for x in WATER_COLOR])
        ratio = count / (resized.size / 3)

        if ratio < 0.9:
            return coords
Exemplo n.º 7
0
def create_plotly_fig_with_line(config, gpx):
    map_options = config['map_options']
    map_options['size'] = (map_options['width'], map_options['height'])
    raw_points = []
    for track in gpx.tracks:
        for segment in track.segments:
            raw_points.extend(segment.points)
    raw_points = simplify_polyline(raw_points,
                                   max_distance=map_options['smoothing_dist'])
    df_raw = df_from_points(raw_points)
    center_lat = (df_raw.latitude.min() + df_raw.latitude.max()) / 2.
    center_long = (df_raw.longitude.min() + df_raw.longitude.max()) / 2.
    mm = geotiler.Map(center=(center_long, center_lat),
                      zoom=map_options['zoom'],
                      size=map_options['size'])
    mm = zoom_map(mm, df_raw.longitude, df_raw.latitude)
    fig = go.FigureWidget(
        go.Scattermapbox(lat=df_raw.latitude,
                         lon=df_raw.longitude,
                         hoverinfo="none",
                         showlegend=False,
                         mode='lines'))
    fig.update_layout(mapbox_style="open-street-map",
                      mapbox=dict(bearing=0,
                                  center=go.layout.mapbox.Center(
                                      lat=mm.center[1], lon=mm.center[0]),
                                  pitch=0,
                                  zoom=mm.zoom))
    fig.update_traces(line=dict(color="Black", width=0.5))
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    return fig
Exemplo n.º 8
0
def gen_map(bbox, start, end, zoom_level=16):
    fig = plt.figure(figsize=(10, 10))
    ax = plt.subplot(111)

    #
    # download background map using OpenStreetMap
    #
    mm = geotiler.Map(extent=bbox, zoom=zoom_level)

    img = geotiler.render_map(mm)
    ax.imshow(img)
    width, height = img.size
    pixels = list(img.getdata())
    pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
    #
    # plot custom points
    #
    x0, y0 = start[1], start[0]
    x1, y1 = end[1], end[0]
    points = ((x0, y0), (x1, y1))
    x, y = zip(*(mm.rev_geocode(p) for p in points))
    ax.scatter(x, y, c='red', edgecolor='none', s=10, alpha=0.9)
    plt.text(x[0], y[0], 'start')
    plt.text(x[1], y[1], 'end')
    plt.savefig('ex-matplotlib.jpg', bbox_inches='tight')
    plt.show()
    plt.close()

    return pixels, width, height
Exemplo n.º 9
0
def get_route_image(route) -> bytes:
    mm = geotiler.Map(extent=route["bbox"], size=(768, 768))
    width, height = mm.size

    img = geotiler.render_map(mm)

    buff = bytearray(img.convert("RGBA").tobytes("raw", "BGRA"))
    surface = cairo.ImageSurface.create_for_data(
        buff, cairo.FORMAT_ARGB32, width, height
    )
    cr = cairo.Context(surface)
    pts = [mm.rev_geocode(pt[::-1]) for pt in polyline.decode(route["geometry"])]
    cr.set_source_rgba(0.0, 0.5, 1.0, 0.5)

    cr.set_line_join(cairo.LINE_JOIN_ROUND)
    cr.set_line_cap(cairo.LINE_CAP_ROUND)
    cr.set_line_width(8)
    cr.move_to(*pts[0])
    for pt in pts:
        cr.line_to(*pt)
    cr.stroke()
    bt = io.BytesIO()
    surface.write_to_png(bt)
    bt.seek(0)
    return bt.read()
Exemplo n.º 10
0
def zoom_map(mm, longitude, latitude):
    lat_min, lat_max = np.min(latitude), np.max(latitude)
    long_min, long_max = np.min(longitude), np.max(longitude)
    zoom = mm.zoom
    while not inside(mm, lat_min, lat_max, long_min, long_max):
        zoom -= 1
        mm = geotiler.Map(center=mm.center, zoom=zoom, size=mm.size)
    return mm
Exemplo n.º 11
0
    def plot_activities_inside_area_on_map(activities: np.array,
                                           area_coordinates: np.array) -> None:
        """
        Static method for plotting the area borders and the activities
        (or their parts) inside of an area.\n
        Args:
            activities (np.array):
                array of AreaIdentification objects
            area_coordinates (np.array):
                border coordinates of an area as an array
                of latitudes and longitudes
        """
        size = 10000
        coordinates = area_coordinates.flatten()
        latitudes = coordinates[::2]
        longitudes = coordinates[1::2]
        map = geotiler.Map(extent=(np.min(longitudes), np.min(latitudes),
                                   np.max(longitudes), np.max(latitudes)),
                           size=(size, size))
        image = geotiler.render_map(map)
        colors = [
            'red', 'blue', 'green', 'cyan', 'magenta', 'yellow', 'key', 'white'
        ]

        # Drawing the map as plot.
        ax = plt.subplot(111)
        ax.imshow(image)
        for i in np.arange(np.shape(activities)[0]):
            sectors = np.array([])
            for j in np.arange(np.shape(activities[i].points_in_area)[0]):
                sectors = np.append(
                    sectors,
                    zip(*(map.rev_geocode(activities[i].positions[p][::-1])
                          for p in np.arange(
                              activities[i].points_in_area[j][0],
                              activities[i].points_in_area[j][1] + 1))))

            # Plotting each activity (displayed only once in legend).
            for j in np.arange(np.shape(sectors)[0]):
                x, y = sectors[j]
                if j == 0:
                    ax.plot(x,
                            y,
                            c=colors[i % 8],
                            label='Activity {}'.format(i + 1))
                else:
                    ax.plot(x, y, c=colors[i % 8], label='_nolegend_')

        # Drawing the bounding box of the chosen area.
        for hull in area_coordinates:
            x, y = zip(*(map.rev_geocode(hull[i - 1][::-1])
                         for i in np.arange(np.shape(hull)[0] + 1)))
            ax.plot(x, y, c='black', label='Area border')

        ax.legend()
        plt.axis('off')
        plt.xlim((0, size))
        plt.ylim((size, 0))
Exemplo n.º 12
0
def setMapZoom(my_map, zoom, img_dict=None):
    img = None
    if (img_dict != None and zoom in img_dict):
        img = img_dict[zoom]
    else:
        mm = geotiler.Map(extent=bbox, zoom=zoom)
        img = geotiler.render_map(mm)
        if (img_dict != None):
            img_dict[zoom] = img
    my_map.imshow(img, origin='upper')
Exemplo n.º 13
0
def get_basemap(mode,zoom,width,provider='stamen-toner'):
    ''' Make a basemap using GeoTiler
        Param mode: Method of getting the map extents.
        Param zoom: Zoom level
        Param width: Width of the map.
        Param provider: The map provider (see the Geotiler library for a list)

        Returns rendered basemap, rendered basemap labels, and map construct.
    '''
    global minx
    global miny
    global maxx
    global maxy
    global map_center_x
    global map_center_y
    size = (width,round(width * 0.75)) #

    if mode == "coordinate":
        # Use our lat/long (in secrets) and map size as the basis for the extent of the map.
        map = geotiler.Map( center=(lat_long[1],lat_long[0]),
                            zoom=zoom,
                            size=size,
                            provider=provider)
        map_labels = geotiler.Map(center=(lat_long[1],lat_long[0]),
                            size=size,
                            zoom=map.zoom,
                            provider='stamen-toner-labels')
        minx, miny, maxx, maxy = map.extent

    else:
        # Use the minx, miny, maxx, maxy extents from the radar layer.
        map = geotiler.Map( extent=(minx, miny, maxx, maxy),
                            zoom=zoom,
                            provider=provider)
        map_labels = geotiler.Map( extent=(minx, miny, maxx, maxy),
                            zoom=map.zoom,
                            provider='stamen-toner-labels')

    (map_center_x,map_center_y) = map.rev_geocode(map.center)
    base_map = geotiler.render_map(map)
    base_map_labels = geotiler.render_map(map_labels)

    return base_map, base_map_labels, map
Exemplo n.º 14
0
    def __init__(self, center, zoom=15, size=(1900, 1000)):
        """
        Create OpenCV compatible map image.

        :param center: Center of the map (longitude and latitude).
        :param zoom: Zoom level of the map.
        :param size: Resolution of the resulting image.
        """
        self.mm = geotiler.Map(center=center, zoom=zoom, size=size)
        self.markers = []
        self.update_map()
Exemplo n.º 15
0
def generate_images_for_segment(segment,
                                zoom=16,
                                size=(256, 256),
                                max_distance=5,
                                render_map=geotiler.render_map,
                                show_route=False,
                                dpi=100):
    width, height = size
    raw_points = segment.points
    if show_route:
        raw_points_lat, raw_points_long = points2array(raw_points)
    for i, (p_long, p_lat) in enumerate(get_points_simplified(raw_points)):
        mm = geotiler.Map(center=(p_long, p_lat), zoom=zoom, size=size)
        p_0_long, p_0_lat, p_1_long, p_1_lat = mm.extent
        img = render_map(mm)
        if show_route:
            fig = plt.figure(figsize=(width / dpi, height / dpi))
            ax = plt.Axes(fig, [0., 0., 1., 1.])
            ax.set_axis_off()
            fig.add_axes(ax)
            ax.imshow(img)
            idx_lat = np.logical_and(p_0_lat <= raw_points_lat,
                                     p_1_lat >= raw_points_lat)
            idx_long = np.logical_and(p_0_long <= raw_points_long,
                                      p_1_long >= raw_points_long)
            idx = np.logical_and(idx_lat, idx_long)
            selected_lat, selected_long = raw_points_lat[idx], raw_points_long[
                idx]
            track = np.array(
                [mm.rev_geocode(p) for p in zip(selected_long, selected_lat)])
            if len(track.shape) > 1:
                ax.plot(track[:, 0],
                        track[:, 1],
                        'r-',
                        alpha=1.0,
                        lw=10,
                        ms=10)
            buf = io.BytesIO()
            fig.savefig(buf, format='png', dpi=dpi)
            buf.seek(0)
            img = Image.open(buf).convert('RGB')
            plt.close(fig)
        else:
            img = img.convert('RGB')
        image_info = dict(zoom=zoom,
                          idx=i,
                          p_0_lat=p_0_lat,
                          p_0_long=p_0_long,
                          p_1_lat=p_1_lat,
                          p_1_long=p_1_long,
                          width=width,
                          height=height,
                          show_route=show_route)
        yield img, image_info
Exemplo n.º 16
0
 def generate_map(self):
     extents = self.extents
     bm = Basemap(llcrnrlon=extents.min['long'],
                  llcrnrlat=extents.min['lat'],
                  urcrnrlon=extents.max['long'],
                  urcrnrlat=extents.max['lat'],
                  projection="merc")
     bm.drawmapboundary()
     self._upper_coords = bm(extents.max['long'], extents.max['lat'])
     gt_map = geotiler.Map(extent=extents.to_tuple(), zoom=17)
     self.mapimg = geotiler.render_map(gt_map)
     return bm
Exemplo n.º 17
0
def create_label_image(label_data: dict, width: int, height: int,
                       bounds: Tuple[float, float, float, float]) -> Image:
    # Create a label image based on the OSM data for the bounds.
    fudged_width = int(round(width * FUDGE_FACTOR))
    fudged_height = int(round(height * FUDGE_FACTOR))
    map_aoi = geotiler.Map(extent=bounds, size=(fudged_width, fudged_height))
    label_image = geotiler.render_map(map_aoi).convert('RGB')

    # Hack the relevant part of the tile out.
    left = (map_aoi.extent[0] - bounds[0]) / (map_aoi.extent[0] -
                                              map_aoi.extent[2]) * fudged_width
    right = (bounds[2] - map_aoi.extent[2]) / (
        map_aoi.extent[0] - map_aoi.extent[2]) * fudged_width

    top = (map_aoi.extent[1] - bounds[1]) / (map_aoi.extent[1] -
                                             map_aoi.extent[3]) * fudged_height
    bottom = (bounds[3] - map_aoi.extent[3]) / (
        map_aoi.extent[1] - map_aoi.extent[3]) * fudged_height

    label_image = label_image.crop(box=(left, top, fudged_width - right,
                                        fudged_height - bottom))
    label_image = label_image.resize((width, height))

    # Tint the label image with a colour based on the disaster code.
    background_image = Image.new("RGBA", (width, height))
    ImageDraw.Draw(background_image, "RGBA").polygon(
        [(0, 0), (height, 0), (height, width), (0, width)],
        BACKGROUND_COLOUR_MAPPING[label_data["metadata"]["disaster"]])
    label_image.paste(background_image, (0, 0), background_image)

    # Add each building to the image (with a colour corresponding to the
    # level of the damage.
    for building in label_data["features"]["xy"]:
        x, y = wkt.loads(building["wkt"]).exterior.coords.xy
        p = list(zip(x, y))
        try:
            colour = DAMAGE_COLOUR_MAPPING[building["properties"]["subtype"]]
        except KeyError:
            # In the case that the building has no 'subtype' property the
            # building is not damaged
            colour = DAMAGE_COLOUR_MAPPING["no-damage"]

        ImageDraw.Draw(label_image).polygon(p, colour)

    return label_image
Exemplo n.º 18
0
    def __init__(self, subPlot=None, gpxData=None):
        GeoSectionViewerGpxData.__init__(self, subPlot, gpxData)

        latitudes, longitudes, elevations, timestamps = self.gpxData.getLatLongElevTs(
        )

        latitudeMax = max(latitudes)
        latitudeMin = min(latitudes)
        longitudeMax = max(longitudes)
        longitudeMin = min(longitudes)
        elevationMax = max(elevations)
        elevationMin = min(elevations)

        scalledMax = 30
        scalledMin = 1

        scalledElevations = [
            ((((point.elevation - elevationMin) * (scalledMax - scalledMin)) /
              (elevationMax - elevationMin)) + scalledMin)
            for i, point in enumerate(self.gpxData)
        ]
        bbox = longitudeMin, latitudeMin, longitudeMax, latitudeMax

        mm = geotiler.Map(extent=bbox, zoom=14)
        img = geotiler.render_map(mm)
        img.save("geotiler.png")

        map = Basemap(llcrnrlon=bbox[0],
                      llcrnrlat=bbox[1],
                      urcrnrlon=bbox[2],
                      urcrnrlat=bbox[3],
                      projection='merc',
                      resolution='i',
                      ax=self.subPlot)
        map.imshow(img, aspect='auto', origin='upper')
        map.scatter(longitudes,
                    latitudes,
                    c='red',
                    s=scalledElevations,
                    marker='o',
                    cmap=cm.hot_r,
                    alpha=0.4,
                    latlon=True)
        map.plot(longitudes, latitudes, 'k', c='red', latlon=True)
Exemplo n.º 19
0
def get_map(points, labels, image_size=(1024, 768)):
    if not points:
        log.err('Cannot show map without point.')
        return None

    border_const = 0.005
    min_lat = min(p[0] for p in points) - border_const
    max_lat = max(p[0] for p in points) + border_const
    min_lon = min(p[1] for p in points) - border_const
    max_lon = max(p[1] for p in points) + border_const

    center = ((min_lon + max_lon) / 2, (min_lat + max_lat) / 2)
    """ count appropriate zoom """
    # https://wiki.openstreetmap.org/wiki/Zoom_levels
    if len(points) == 1:
        zoom = 18
    else:
        zoom = 0
        tmp_tile_width = 360
        while (tmp_tile_width > abs(max_lon - min_lon)
               and tmp_tile_width/2 > abs(max_lat - min_lat)):
            #print('Zoom', zoom, 'TTW', tmp_tile_width, 'latdiff', abs(max_lat - min_lat), 'londiff', abs(max_lon - min_lon))
            tmp_tile_width /= 2
            zoom += 1
        zoom = min(18, max(1, zoom + 1))
        #print('Center:', center)
        #print('Zoom:', zoom)

    fig = plt.figure(figsize=(20, 15), frameon=False)
    ax = plt.subplot(111)
    mm = geotiler.Map(center=center, size=image_size,
                      zoom=zoom, provider='osm')
    img = geotiler.render_map(mm)
    geo_points = [mm.rev_geocode(p[::-1]) for p in points]
    X, Y = zip(*geo_points)
    ax.axis('off')  # TODO remove border
    ax.imshow(img)
    ax.scatter(X, Y, marker='p', c='darkgreen',
               edgecolor='none', s=500, alpha=0.8)
    for x, y, label in zip(X, Y, labels):
        #ax.annotate(label, (x, y), (x+5, y-5))
        ax.text(x+5, y-5, label, fontsize=30)
        # TODO change positioning if overlap is expected
    return fig
Exemplo n.º 20
0
def draw_alignment(track1, track2, bounds):
    """ Draws the aligned tracks with the given bounds onto a cairo surface. """

    _log.info("Drawing alignment")

    mm = geotiler.Map(extent=bounds, zoom=14)
    width, height = mm.size
    image = geotiler.render_map(mm)

    # create cairo surface
    buff = bytearray(image.convert('RGBA').tobytes('raw', 'BGRA'))
    surface = cairo.ImageSurface.create_for_data(buff, cairo.FORMAT_ARGB32,
                                                 width, height)
    cr = cairo.Context(surface)

    a1_l = len(track1)
    a2_l = len(track2)
    assert a1_l == a2_l
    p_radius = 2
    for i in range(0, a1_l):
        if a1[i] is not None and a2[i] is not None:
            cr.set_source_rgba(0.2, 0.7, 1.0, 1.0)
            a1_x, a1_y = mm.rev_geocode((a1[i].longitude, a1[i].latitude))
            cr.arc(a1_x, a1_y, p_radius, 0, 2 * math.pi)
            cr.fill()
            cr.set_source_rgba(0.0, 0.0, 1.0, 1.0)
            a2_x, a2_y = mm.rev_geocode((a2[i].longitude, a2[i].latitude))
            cr.arc(a2_x, a2_y, p_radius, 0, 2 * math.pi)
            cr.fill()
        elif a1[i] is not None and a2[i] is None:
            cr.set_source_rgba(1.0, 0.0, 0.0, 1.0)
            a1_x, a1_y = mm.rev_geocode((a1[i].longitude, a1[i].latitude))
            cr.arc(a1_x, a1_y, p_radius, 0, 2 * math.pi)
            cr.fill()
        elif a1[i] is None and a2[i] is not None:
            cr.set_source_rgba(1.0, 0.5, 0.0, 1.0)
            a2_x, a2_y = mm.rev_geocode((a2[i].longitude, a2[i].latitude))
            cr.arc(a2_x, a2_y, p_radius, 0, 2 * math.pi)
            cr.fill()
    return surface
Exemplo n.º 21
0
def draw_track(track, bounds):
    """ Draws the given tracks with the given bounds onto a cairo surface. """

    _log.info("Drawing track")

    mm = geotiler.Map(extent=bounds, zoom=14)
    width, height = mm.size
    image = geotiler.render_map(mm)

    # create cairo surface
    buff = bytearray(image.convert('RGBA').tobytes('raw', 'BGRA'))
    surface = cairo.ImageSurface.create_for_data(buff, cairo.FORMAT_ARGB32,
                                                 width, height)
    cr = cairo.Context(surface)

    p_radius = 2
    for p in track:
        cr.set_source_rgba(0.0, 0.0, 1.0, 1.0)
        a1_x, a1_y = mm.rev_geocode((p.longitude, p.latitude))
        cr.arc(a1_x, a1_y, p_radius, 0, 2 * math.pi)
        cr.fill()
    return surface
Exemplo n.º 22
0
def get_points_simplified(raw_points,
                          max_distance=5,
                          zoom=16,
                          size=(512, 512)):
    if max_distance is not None:
        points = simplify_polyline(raw_points, max_distance=max_distance)
    else:
        points = raw_points
    df = df_from_points(points)
    f_lat, f_long = interp1d(df.distance_total,
                             df.latitude), interp1d(df.distance_total,
                                                    df.longitude)
    mm_zero = geotiler.Map(center=(points[0].longitude, points[0].latitude),
                           zoom=zoom,
                           size=size)
    p_0_long, p_0_lat, p_1_long, p_1_lat = mm_zero.extent
    distance = GPXTrackPoint(latitude=p_0_lat, longitude=p_1_long).distance_2d(
        GPXTrackPoint(latitude=p_1_lat, longitude=p_0_long))
    steps = np.arange(df.distance_total.values[0],
                      df.distance_total.values[-1],
                      distance / (2. * 1.41421356237))
    for d in steps:
        yield f_long(d), f_lat(d)
Exemplo n.º 23
0
    def plot2D(self):
        gpx_bounds = self._gpx.get_bounds()
        bbox = [
            gpx_bounds.min_longitude - 0.002, gpx_bounds.min_latitude - 0.002,
            gpx_bounds.max_longitude + 0.002, gpx_bounds.max_latitude + 0.002
        ]

        fig = plt.figure(figsize=(13, 13))
        ax = plt.subplot(111)

        # download tiles from OSM
        mm = geotiler.Map(extent=bbox, zoom=16)
        img = geotiler.render_map(mm)

        myMap = Basemap(llcrnrlon=bbox[0],
                        llcrnrlat=bbox[1],
                        urcrnrlon=bbox[2],
                        urcrnrlat=bbox[3],
                        projection='merc',
                        ax=ax)
        myMap.imshow(img, interpolation='lanczos', origin='upper')

        # plot hike
        points = self._gpx.get_points_data()
        lon = [p[0].longitude for p in points]
        lat = [p[0].latitude for p in points]
        index = [p.point_no for p in points]  # color sequentially each point

        x, y = myMap(lon, lat)  # map (long, lat) to (x,y) coordinates in plot
        ax.scatter(x, y, c=index, s=4, cmap='brg')

        print("Printing map in", self._out_dir + '/map.png')
        plt.savefig(self._out_dir + '/map.png',
                    quality=100,
                    bbox_inches='tight')
        plt.close()
Exemplo n.º 24
0
        if 'lon' in data:
            await queue.put((data['lon'], data['lat']))


async def show_map(queue, map):
    """
    Save map centered at location to a file.
    """
    while True:
        pos = yield from queue.get()

        map.center = pos
        img = await render_map_async(map)
        img.save('ex-async-gps.png', 'png')


size = 800, 800
start = 0, 0
mm = geotiler.Map(size=size, center=start, zoom=16)

queue = asyncio.Queue(1)  # queue holding current position from gpsd

# run location and map rendering tasks concurrently
t1 = show_map(queue, mm)
t2 = read_gps(queue)
task = asyncio.gather(t1, t2)
loop = asyncio.get_event_loop()
loop.run_until_complete(task)

# vim: sw=4:et:ai
Exemplo n.º 25
0
        scroll_map(self, self.position)


# bind Qt application with Python asyncio loop
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)

g = app.desktop().screenGeometry()
size = g.width() + 256 * 2, g.height() + 256 * 2

pos = (0, 0)
if len(sys.argv) == 3:
    pos = float(sys.argv[1]), float(sys.argv[2])

mm = geotiler.Map(size=size, center=pos, zoom=18)

window = MapWindow(mm)
window.show()

queue = asyncio.Queue()
t1 = read_gps(queue)
t2 = locate(window, queue)
t3 = refresh_map(window)
task = asyncio.gather(t1, t2, t3)

window.refresh_map.set()
loop.run_until_complete(task)

# vim: sw=4:et:ai
Exemplo n.º 26
0
from mpl_toolkits.basemap import Basemap

import logging
logging.basicConfig(level=logging.DEBUG)

import geotiler

bbox = 11.78560, 46.48083, 11.79067, 46.48283

fig = plt.figure(figsize=(10, 10))
ax = plt.subplot(111)

#
# download background map using OpenStreetMap
#
mm = geotiler.Map(extent=bbox, zoom=18)

img = geotiler.render_map(mm)

#
# create basemap
#
map = Basemap(llcrnrlon=bbox[0],
              llcrnrlat=bbox[1],
              urcrnrlon=bbox[2],
              urcrnrlat=bbox[3],
              projection='merc',
              ax=ax)

map.imshow(img, interpolation='lanczos', origin='upper')
Exemplo n.º 27
0
    def plot_map(self) -> None:
        """
        Method for plotting the map using Geotiler
        according to the object variables.
        """
        if np.shape(self.positions)[0] == 0:
            raise Exception('Dataset is empty or invalid.')

        # Downloading the map.
        size = 10000
        coordinates = self.positions.flatten()
        latitudes = coordinates[::2]
        longitudes = coordinates[1::2]
        map = geotiler.Map(extent=(np.min(longitudes), np.min(latitudes),
                                   np.max(longitudes), np.max(latitudes)),
                           size=(size, size))
        image = geotiler.render_map(map)

        # Drawing the map as plot.
        ax = plt.subplot(111)
        ax.imshow(image)

        # If there are some points inside of the given area,
        # the segments outside and inside of the area are plotted
        # on the map.
        if np.shape(self.points_in_area)[0] > 0:
            # Drawing the starting path outside of the area.
            x, y = zip(*(map.rev_geocode(self.positions[p][::-1])
                         for p in np.arange(0, self.points_in_area[0][0] + 1)))
            ax.plot(x, y, c='blue', label='Outside of the area')

            # Drawing the path inside of the area and possible paths
            # in between outside of the area.
            for i in np.arange(np.shape(self.points_in_area)[0]):
                x, y = zip(*(map.rev_geocode(self.positions[p][::-1])
                             for p in np.arange(self.points_in_area[i][0],
                                                self.points_in_area[i][1] +
                                                1)))

                if i == 0:
                    ax.plot(x,
                            y,
                            c='red',
                            label='Part of exercise inside of the area')
                else:
                    ax.plot(x, y, c='red', label='_nolegend_')

                if np.shape(self.points_in_area)[0] > i + 1:
                    x, y = zip(
                        *(map.rev_geocode(self.positions[p][::-1])
                          for p in np.arange(self.points_in_area[i][1],
                                             self.points_in_area[i + 1][0] +
                                             1)))
                    ax.plot(x, y, c='blue', label='_nolegend_')

            # Drawing the ending path outside of the area.
            x, y = zip(*(map.rev_geocode(self.positions[p][::-1])
                         for p in np.arange(self.points_in_area[-1][1],
                                            np.shape(self.positions)[0])))
            ax.plot(x, y, c='blue', label='_nolegend_')
        # If there are no points inside of the given area,
        # the whole path is plotted as outside of the given area.
        else:
            x, y = zip(*(map.rev_geocode(self.positions[p][::-1])
                         for p in np.arange(np.shape(self.positions)[0])))
            ax.plot(x,
                    y,
                    c='blue',
                    label='Part of exercise outside of the area')

        # Drawing the bounding box of the chosen area.
        for hull in self.area_coordinates:
            x, y = zip(*(map.rev_geocode(hull[i - 1][::-1])
                         for i in np.arange(np.shape(hull)[0] + 1)))
            ax.plot(x, y, c='black', label='Area border')

        ax.legend()
        plt.axis('off')
        plt.xlim((0, size))
        plt.ylim((size, 0))
Exemplo n.º 28
0
#
"""
Python Geocoder example.
"""

import geocoder

import logging
logging.basicConfig(level=logging.DEBUG)

import geotiler

#
# find coordinates of Moscone Center
#
gc = geocoder.google('Moscone Center')
y, x = gc.latlng

#
# download map using OpenStreetMap
#
mm = geotiler.Map(center=(x, y), zoom=18, size=(512, 512))
img = geotiler.render_map(mm)

#
# save map image as PNG file
#
img.save('ex-geocoder.png')

# vim: sw=4:et:ai
Exemplo n.º 29
0
        """
        Close the shelve used to cache the data.
        """
        self.cache.close()


# Create a cache instance
cache = Cache("test")

# Create a new downloader using the shelve cache
downloader = partial(caching_downloader, cache.get, cache.set, fetch_tiles)

# Set render_map to use new downloader function
render_map = partial(geotiler.render_map, downloader=downloader)

mm = geotiler.Map(center=(0.0, 51.47879), zoom=18, size=(1900, 1000))

# Render map for first time and save current time
t1 = time.time()
img = render_map(mm)
t2 = time.time()

# Render map for the second time to demonstrate the speed of the cache
img = render_map(mm)
t3 = time.time()

# Close the cache
cache.close()

print('time for first render: {:6.5f} seconds'.format(t2 - t1))
print('time for second render: {:6.5f} seconds'.format(t3 - t2))
Exemplo n.º 30
0
from mpl_toolkits.basemap import Basemap
import matplotlib.animation as animation
import numpy as np

#lon, lat
london_aquatics_centre = (-.0105, 51.5404)
london_aquatics_centre_corners = (
                                  -0.0184,        #lower left corner longitude
                                  51.5378,        #lower left corner latitude
                                  -0.0074,        #upper right corner longitude
                                  51.5437,        #upper right corner latitude
                                  )
zoom = 16
figure = plt.figure(figsize=(16, 9))
ax = plt.subplot(111)
m = geotiler.Map(extent=london_aquatics_centre_corners, zoom=zoom)
img = geotiler.render_map(m)


bmap = Basemap(
    llcrnrlon=london_aquatics_centre_corners[0], llcrnrlat=london_aquatics_centre_corners[1],
    urcrnrlon=london_aquatics_centre_corners[2], urcrnrlat=london_aquatics_centre_corners[3],
    projection="merc", ax=ax
)

bmap.imshow(img, interpolation='lanczos', origin='upper')
# x, y = bmap(london_aquatics_centre[0], london_aquatics_centre[1])

aa = np.array( [[-0.0097, 51.5407],
               [-0.0120, 51.5417],
               [-0.0158, 51.5407],