예제 #1
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()
예제 #2
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
예제 #3
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)
예제 #4
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
예제 #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()
예제 #6
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)
    def draw(self, filename):
        self.acc = tuple((np.array(self.acc) / self.mbp / 2) ** 2) # accuracy in pixel

        x, y = self.__get_coord_meters()
        logging.debug((x, y))

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

        img = geotiler.render_map(self.mm)
        ax.imshow(img)

        ax.scatter(x, y, c=self.colors, edgecolor=self.colors, s=self.acc, alpha=.2)
        ax.plot(x, y)
        for i, txt in enumerate(self.annot):
            if txt:
                if len(txt) < 4:
                    color = 'g'
                else:
                    color = np.random.rand(3,)
                xylim = 15
                xtext = -xylim if i % 4 == 0 else xylim
                ytext = -xylim if i % 4 < 2 else xylim
                ax.annotate(txt, xy=(x[i], y[i]), xytext=(xtext, ytext), color=color,
                            textcoords='offset points', ha='center', va='bottom', size='xx-small',
                            arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',color=color))

        plt.savefig(filename, bbox_inches='tight')
        plt.close()
예제 #8
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
예제 #9
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))
예제 #10
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
예제 #11
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')
    def _init_basemap(self):
        self.m = geotiler.Map(extent=self.corners, zoom=self.zoom)
        self.img = geotiler.render_map(self.m)
        self.bmap = Basemap(
            llcrnrlon=self.corners[0], llcrnrlat=self.corners[1],
            urcrnrlon=self.corners[2], urcrnrlat=self.corners[3],
            projection="merc", ax=self.ax
        )

        self.bmap.imshow(self.img, interpolation='lanczos', origin='upper')
예제 #13
0
파일: core.py 프로젝트: jasony37/roadgest
 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
예제 #14
0
    def __init__(self, subPlot = None, gpxData = None, geoMarkers = 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)
        self.rawMapImage = geotiler.render_map(mm)

        map = Basemap(
            llcrnrlon=bbox[0], llcrnrlat=bbox[1],
            urcrnrlon=bbox[2], urcrnrlat=bbox[3],
            projection='merc',
            resolution='i',
            ax=self.subPlot)
        map.imshow(self.rawMapImage, aspect='auto', origin='upper')
        #--draw path
        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)
        #--draw labels
        if(geoMarkers is not None):
            for geoMarker in geoMarkers:
                xy = map(geoMarker["longitude"], geoMarker["latitude"])
        #
        #         subPlot.annotate(
        #             geoMarker["name"],
        #             xy, xytext = (-20, 20),
        #             textcoords = 'offset points', ha = 'right', va = 'bottom',
        #     #        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
        #             bbox = dict(fc = 'yellow', alpha = 0.5),
        #             arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
        #
                subPlot.text(xy[0], xy[1], "{0}-{1} {2}".format(geoMarker["name"], geoMarker["elevation"], geoMarker["time"]),fontsize=9,
                                ha='center',va='top',color='r',
#                                bbox = dict(ec='None',fc=(1,1,1,0.5)))
                                bbox = dict(fc = 'yellow', alpha = 0.5))
예제 #15
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
예제 #16
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
예제 #17
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)
예제 #18
0
파일: cmpgpx.py 프로젝트: jonblack/cmpgpx
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
예제 #19
0
파일: cmpgpx.py 프로젝트: tripliks/cmpgpx
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
예제 #20
0
파일: gfx.py 프로젝트: jonblack/cmpgpx
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
예제 #21
0
파일: gfx.py 프로젝트: tripliks/cmpgpx
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
예제 #22
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()
예제 #23
0
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)
ax.imshow(img)

#
# plot custom points
#
x0, y0 = 11.78816, 46.48114 # http://www.openstreetmap.org/search?query=46.48114%2C11.78816
x1, y1 = 11.78771, 46.48165 # http://www.openstreetmap.org/search?query=46.48165%2C11.78771
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.savefig('ex-matplotlib.pdf', bbox_inches='tight')
plt.close()

# vim: sw=4:et:ai
예제 #24
0
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')

#
# plot custom points
예제 #25
0
 def get_osm(self, *args, provider='osm', **kwargs):
     #geotiler cannot handle the bbox to be of type numpy, so convert to native floats:
     bbox = [x.item() for x in self.get_bbox_latlon(format='lonlat')]
     gm = geotiler.Map(extent=bbox, zoom=self.get_osm_zoom_level(bbox), provider=provider)
     self.img = geotiler.render_map(gm)
     return self.mm.imshow(self.img, *args, interpolation='lanczos', origin='upper', **kwargs)
예제 #26
0
def draw_map(world_data, name, size, zoom, latitude, longitude, legend=0):
    print("https://maps.luftdaten.info/#%i/%0.2f/%0.2f" %
          (zoom, latitude, longitude))

    hexagons = []
    height, width = size
    tile_pair_h = 3 * hex_h2
    tile_w = 2 * hex_w2
    for row_pair in range(1 + int(height // tile_pair_h)):
        for col in range(1 + int(width // tile_w)):
            hexagons.append(Hexagon(col * tile_w, row_pair * tile_pair_h))
            hexagons.append(
                Hexagon(col * tile_w + hex_w2,
                        row_pair * tile_pair_h + hex_h2 + hex_h4))

    # Will use geotiler for map in background
    background_filename = "%s-background.png" % name
    geotiler_map = geotiler.Map(center=(longitude, latitude),
                                zoom=zoom,
                                size=size)
    min_long, min_lat, max_long, max_lat = map_extent = geotiler_map.extent
    if not os.path.isfile(background_filename):
        print("Fetching %s background" % name)
        map_img = geotiler.render_map(geotiler_map)
        map_img.save(background_filename)
    else:
        print("Loading %s background" % name)
        map_img = Image.open(background_filename)
    assert size == map_img.size

    # TODO - Apply filters to make the background muted
    # See https://www.w3schools.com/CSSref/css3_pr_filter.asp
    # and https://github.com/opendata-stuttgart/feinstaub-map/blob/master/src/style.style
    # img.leaflet-tile
    # filter  grayscale(85%) saturate(150%) hue-rotate(60deg) contrast(90%) brightness(110%)

    if legend:
        map_img.paste(legend_img, legend)
    else:
        map_img.paste(legend_img)

    data = [
        row for row in world_data
        if row["location"]["longitude"] and row["location"]["latitude"]
        and min_long <= float(row["location"]["longitude"]) <= max_long
        and min_lat <= float(row["location"]["latitude"]) <= max_lat
    ]
    print("Have %i points with map extent" % len(data))

    data_pm10 = []
    data_long = []
    data_lat = []
    for row in data:
        for sensor_data_value in row["sensordatavalues"]:
            if sensor_data_value["value_type"] == "P1":
                data_pm10.append(float(sensor_data_value["value"]))
                data_long.append(float(row["location"]["longitude"]))
                data_lat.append(float(row["location"]["latitude"]))

    data_x, data_y = zip(*(geotiler_map.rev_geocode(p)
                           for p in zip(data_long, data_lat)))

    print("%i PM 10, %i long, %i lat" %
          (len(data_pm10), len(data_long), len(data_lat)))
    assert len(data_pm10) == len(data_long) == len(data_lat)

    # Make a blank image for the hexagon overlay,
    # initialized to a completely transparent color.
    hex_img = Image.new("RGBA", size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(hex_img, "RGBA")
    for x, y, value in zip(data_x, data_y, data_pm10):
        for hex in hexagons:
            if (x, y) in hex:
                hex.data.append(value)
                break

    print("Worst hexagon mean PM 10 value %0.2f ug/m3" %
          max(mean(_.data) for _ in hexagons if _.data))
    print("Worst PM 10 sensor value %0.2f ug/m3" % max(data_pm10))

    for hex in hexagons:
        if hex.data:
            draw.polygon(hex.polygon(), hex.color())
        # else:
        #     draw.polygon(hex.polygon(), (0,0,0xff,0xC0))

    # Debug code to check hexagons contain the points
    # for x, y, value in zip(data_x, data_y, data_pm10):
    #     if value:
    #         draw.polygon(
    #             [(x - 5, y - 5), (x - 5, y + 5), (x + 5, y + 5), (x + 5, y - 5)],
    #             (255, 0, 255, 125),
    #         )

    # Alpha composite the two images together.
    img = Image.alpha_composite(map_img, hex_img)
    img.save("%s.png" % name)
    print("%s done" % name)
예제 #27
0
    count = cv.countNonZero(dst)
    return count


WATER_COLOR = [223, 211, 170]

start_time = time.time()
asyncio.set_event_loop(asyncio.new_event_loop())
resized: np.ndarray
while True:
    coords = random_coords()
    print(f'{coords.lat}, {coords.lng}')
    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)

    print(resized.size)
    count = countPixelsInRange(resized, [x - 5 for x in WATER_COLOR],
                               [x + 5 for x in WATER_COLOR])
    print(count)
    ratio = count / (resized.size / 3)
    print(ratio)
예제 #28
0
    def show_map(self) -> plt:
        """
        Method for plotting the exercise with dead ends.
        Returns:
            plt
        """
        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 the given area, the
        # segments outside and inside of the area are plotted
        # on the map.
        if np.shape(self.dead_ends)[0] > 0:
            # Drawing the starting path with no dead end.
            x, y = zip(
                *(map.rev_geocode(self.positions[p][::-1])
                  for p in np.arange(
                      0,
                      self.dead_ends[0][0] + 1
                  ))
            )
            ax.plot(x, y, c='blue', label='No dead end')

            # Drawing the path within the dead end.
            for i in np.arange(np.shape(self.dead_ends)[0]):
                x, y = zip(
                    *(map.rev_geocode(self.positions[p][::-1])
                      for p in np.arange(
                          self.dead_ends[i][0],
                          self.dead_ends[i][1] + 1
                      ))
                )

                if i == 0:
                    ax.plot(x, y, c='red', label='Dead end')
                else:
                    ax.plot(x, y, c='green', label='_nolegend_')

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

            # Drawing the ending path with no dead end.
            x, y = zip(
                *(map.rev_geocode(self.positions[p][::-1])
                  for p in np.arange(
                      self.dead_ends[-1][1],
                      np.shape(self.positions)[0]
                  ))
            )
            ax.plot(x, y, c='blue', label='_nolegend_')
        # If there are no points inside 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='No dead end')

        ax.legend()
        plt.axis('off')
        plt.xlim((0, size))
        plt.ylim((size, 0))
        return plt
예제 #29
0
 def __genmap(self, last: tuple):
     m = geotiler.Map(center=(last[1], last[0]), zoom=18, size=(768, 600))
     self.__mapextent = deepcopy(m.extent)
     img = geotiler.render_map(m)
     self.__mapimg = itk.PhotoImage(img)
예제 #30
0
    def __init__(self, subPlot=None, gpxData=None, geoMarkers=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)
        self.rawMapImage = geotiler.render_map(mm)

        map = Basemap(llcrnrlon=bbox[0],
                      llcrnrlat=bbox[1],
                      urcrnrlon=bbox[2],
                      urcrnrlat=bbox[3],
                      projection='merc',
                      resolution='i',
                      ax=self.subPlot)
        map.imshow(self.rawMapImage, aspect='auto', origin='upper')
        #--draw path
        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)
        #--draw labels
        if (geoMarkers is not None):
            for geoMarker in geoMarkers:
                xy = map(geoMarker["longitude"], geoMarker["latitude"])
                #
                #         subPlot.annotate(
                #             geoMarker["name"],
                #             xy, xytext = (-20, 20),
                #             textcoords = 'offset points', ha = 'right', va = 'bottom',
                #     #        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
                #             bbox = dict(fc = 'yellow', alpha = 0.5),
                #             arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
                #
                subPlot.text(
                    xy[0],
                    xy[1],
                    "{0}-{1} {2}".format(geoMarker["name"],
                                         geoMarker["elevation"],
                                         geoMarker["time"]),
                    fontsize=9,
                    ha='center',
                    va='top',
                    color='r',
                    #                                bbox = dict(ec='None',fc=(1,1,1,0.5)))
                    bbox=dict(fc='yellow', alpha=0.5))
예제 #31
0
 def update_map(self):
     """
     Download new map tiles and redraw everyting on the map.
     """
     self.pil_image = geotiler.render_map(self.mm)
     self.draw_map()
예제 #32
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))
예제 #33
0
 def update_map(self):
     """
     Download new map tiles and redraw everyting on the map.
     """
     self.pil_image = geotiler.render_map(self.mm)
     self.draw_map()