Ejemplo n.º 1
0
    def _create_control(self, parent):
        control = QMapWidget()
        # control.setMaximumSize(200,200)
        lat_min = 34.052999
        lon_min = -106.924551
        lat_max = 34.076752
        lon_max = -106.885971
        #
        # lat_min = 34.052999
        # lon_min = -106.81
        # lat_max = 34.08
        # lon_max = -106.83
        rect = (lat_min, lon_min, lat_max, lon_max)
        server = 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png'
        server = 'http://c.tile.stamen.com/watercolor/{z}/{x}/{y}.png'
        # server = 'https://c.tiles.wmflabs.org/hillshading/{z}/{x}{y}.png'
        # server = 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}'  # satelite
        # server = 'https://mt1.google.com/vt/lyrs=t&x={x}&y={y}&z={z}'  # terrain
        # server = 'https://mt1.google.com/vt/lyrs=r&x={x}&y={y}&z={z}'  # maps

        smopy.TILE_SERVER = server
        m = smopy.Map(rect, z=10)
        # m = smopy.Map(rect)
        # m = smopy.Map(lat_min, lon_min, z=10, tileserver='http://c.tile.stamen.com/watercolor/{z}/{x}/{y}.png')

        # m.show_ipython()
        # control.set_tile(m.img)
        base = m.img
        base = base.convert('RGBA')
        base.putalpha(200)
        control.set_tile(base)

        # return control

        server = 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png'
        # server = 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}'  # satelite

        smopy.TILE_SERVER = server
        m = smopy.Map(rect, z=10)
        # img = m.img
        # img = img.convert('RGBA')
        # img.putalpha(128)
        # img = img.convert('RGB')

        img = m.img.convert('RGBA')
        img.putalpha(128)

        img = Image.alpha_composite(base, img)

        control.set_tile(img)
        # control.set_tile(Image.blend(base, l1, 129))
        # m.show_mpl()
        # from matplotlib.pyplot import show
        # show()

        # control.set_screen()
        return control
Ejemplo n.º 2
0
def generate_preview(lat, lon):
    osm_map = smopy.Map((lat-0.5, lon-0.5, lat+0.5, lon+0.5), z=9).to_pil()
    weather_map = smopy.Map((lat-0.5, lon-0.5, lat+0.5, lon+0.5), z=9,
            tileserver="http://a.tileserver.unimplemented.org/data/FX_015-latest/{z}/{x}/{y}.png").to_pil()

    random_name = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(128))
    pathspec = "/pushpreview/%s.png" % random_name

    out = Image.blend(osm_map, weather_map, 0.4).convert("RGB")
    # out is 768 × 768 pixels
    #out.crop((100,100, 668,668)).save("/pushpreview/%s.png" % random_name, format="png", optimize=True)
    out.save(pathspec, format="png", optimize=True)

    return "https://meteocool.unimplemented.org%s" % pathspec
Ejemplo n.º 3
0
    def showcov(self,
                triang,
                val,
                vmin=-130,
                vmax=-50,
                cmap=plt.cm.jet,
                bbuild=False,
                btile=True):
        """ Show a coverage

        Parameters
        ----------

        triang : triangulation
        val : values

        """
        lonmin = np.min(triang.x)
        lonmax = np.max(triang.x)
        latmin = np.min(triang.y)
        latmax = np.max(triang.y)
        extent = (lonmin, lonmax, latmin, latmax)
        print(extent)
        mp = smopy.Map((extent[2] + 0.1, extent[0] + 0.1, extent[3] - 0.1,
                        extent[1] - 0.1),
                       z=12)
        if bbuild:
            f, ax, d = self.show(fig=f,
                                 ax=ax,
                                 contour=False,
                                 btile=False,
                                 bldg=True,
                                 height=False,
                                 coord='lonlat',
                                 extent=self.extent)

        #ax = plt.gca()
        if mp != []:
            triang.x, triang.y = mp.to_pixels(triang.y, triang.x)
        #ax = mp.show_mpl(figsize=(10,10))
        ax = plt.gca()
        tc = ax.tripcolor(
            triang,
            val.flatten(),
            #shading='gouraud',
            #shading='flat',
            cmap=cmap,
            vmax=vmax,
            vmin=vmin,
            alpha=0.4,
            edgecolors='k',
            linewidth=0.0)
        #plt.axis('equal')
        ax = mp.show_mpl(ax=ax)

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad="5%")
        cb = colorbar(tc, cax=cax)
        cb.set_label_text('Loss(dB)', fontsize=18)
        return (cb)
Ejemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        super().__init__('Ground Station Software')

        self.mapCenterLat = 41.0730202
        self.mapCenterLong = -72.0839729

        # Definition of the forms fields
        self._runbutton = ControlButton('Run')
        self._mapImage = ControlImage('map')

        self.scaleyboi = 18
        newmap = smopy.Map(
            (self.mapCenterLat - mapScale[self.scaleyboi] / 2,
             self.mapCenterLong - mapScale[self.scaleyboi] / 2,
             self.mapCenterLat + mapScale[self.scaleyboi] / 2,
             self.mapCenterLong + mapScale[self.scaleyboi] / 2),
            z=self.scaleyboi,
            tileserver='http://192.168.1.152/osm_tiles/{z}/{x}/{y}.png')
        self.blank_map = newmap
        self.map = self.blank_map.to_numpy()
        self._mapImage.value = self.map

        self._runbutton.value = self.run_event

        # Define the organization of the Form Controls
        self.formset = [{'Tab1': ['_runbutton'], 'Tab2': ['_mapImage']}]

        self.update_my_loc_handler()
        self.update_map_center_handler()
def get_map(coords):
    map = smopy.Map((coords['lat_min'], coords['lon_min'], coords['lat_max'],
                     coords['lon_max']),
                    z=8)
    ax = map.show_mpl(figsize=(8, 8))
    plt.show()
    return True
Ejemplo n.º 6
0
Archivo: main.py Proyecto: hansthen/ret
    def show_map(self, name):
        """Display the map for a location"""
        g = geocoder.osm(name)
        bbox = g.json["bbox"]
        bbox = bbox["northeast"] + bbox["southwest"]
        map_ = smopy.Map(bbox, zoom=11)
        logging.debug("Bounding box: %s", map_.box)
        ax = map_.show_mpl(figsize=(10, 6))
        xs = []
        ys = []

        # This show all stops on the map, also not the ones
        # used for processing, but heck . . .
        for stop in self.stops.values():
            x, y = map_.to_pixels(float(stop[3]), float(stop[4]))
            xs.append(x)
            ys.append(y)

        plt.ion()
        plt.show()
        ax.plot(xs, ys, ".c")

        # Plot the tracks in blue
        for shape in self.shapes.values():
            xys = [
                map_.to_pixels(element.shape_pt_lat, element.shape_pt_lon)
                for element in shape
            ]

            xs = [elem[0] for elem in xys]
            ys = [elem[1] for elem in xys]
            ax.plot(xs, ys, "-b")

        plt.pause(0.001)
        return map_, ax
Ejemplo n.º 7
0
def find_mid_nodes(map_con, matcher):
    coords_list = []
    coord_trans = None
    ax = None

    z = 18

    bb = map_con.bb()
    m = smopy.Map(bb, z=z, ax=ax)

    if matcher is not None:
        lat_nodes = matcher.lattice_best
    else:
        lat_nodes = None

    for idx, m in enumerate(lat_nodes):
        lat, lon = m.edge_m.pi[:2]
        #lat2, lon2 = m.edge_o.pi[:2]

        if coord_trans:
            #   lat, lon = coord_trans(lat, lon)
            lat2, lon2 = coord_trans(lat2, lon2)

        x, y = to_pixels(lat, lon)
        #x2, y2 = to_pixels(lat2, lon2)
        coords_list.append((y, x))

    return coords_list
Ejemplo n.º 8
0
    def load_map(self, lat0=42, lat1=-1, lon0=55, lon1=3, zoom=3):
        """
        Load a map image into the widget
        :param lat0:
        :param lat1:
        :param lon0:
        :param lon1:
        :param zoom: 1~14
        """
        # store coordinates
        self.lat0 = lat0
        self.lat1 = lat1
        self.lon0 = lon0
        self.lon1 = lon1
        self.zoom = zoom

        # get map
        map = smopy.Map((lat0, lat1, lon0, lon1), z=zoom)

        w, h = map.img.size
        self.img = ImageQt(map.img)
        self.image = QPixmap.fromImage(self.img)

        # resize widget
        self.setRect(0.0, 0.0, w, h)
Ejemplo n.º 9
0
 def print_grid_initial_ireland(self):
     worldmap2 = smopy.Map((42., -1., 55., 3.), z=4)
     numcities = len(self.initialguess)
     fig, ax = plt.subplots(1, 1, figsize=(10, 10))
     ax.set_xticks([])
     ax.set_yticks([])
     ax.grid(False)
     ax.set_xlim(0, worldmap2.w)
     ax.set_ylim(worldmap2.h, 0)
     ax.axis('off')
     plt.tight_layout()
     ax.imshow(worldmap2.img)
     '''generate points corresponding to cities'''
     px, py = [], []
     for i in range(0, (numcities)):
         plotx, ploty = worldmap2.to_pixels(self.initialguess[i].lat,
                                            self.initialguess[i].lon)
         px.append(plotx)
         py.append(ploty)
     fit = self.fitness(self.initialguess)
     s = 'Initial Path length: %f' % fit
     ax.plot(px, py, 'ro', label=s)
     ax.legend(loc=1)
     '''generate points corresponding to paths'''
     colours = ['b', 'g', 'k', 'y', 'c', 'm']
     for j in range(0, (numcities)):
         pathlat, pathlon = gcd_path(
             self.initialguess[j].lat, self.initialguess[j].lon,
             self.initialguess[(j + 1) % numcities].lat,
             self.initialguess[(j + 1) % numcities].lon, 10)
         pathx, pathy = worldmap.to_pixels(pathlat, pathlon)
         ax.plot(pathx, pathy, colours[j % 6])
     fig.show()
Ejemplo n.º 10
0
def get_smopy_map(lat_min, lat_max, lon_min, lon_max, z):
    args = (lat_min, lat_max, lon_min, lon_max, z)
    if args not in get_smopy_map.maps:
        smopy.Map.get_allowed_zoom = lambda self, z: z
        get_smopy_map.maps[args] = smopy.Map(
            (lat_min, lon_min, lat_max, lon_max), z=z)
    return get_smopy_map.maps[args]
Ejemplo n.º 11
0
def get_smopy_map(lon_min, lon_max, lat_min, lat_max, z=None, map_style=None):
    ORIG_TILE_SERVER = smopy.TILE_SERVER
    if map_style is not None:
        assert map_style in MAP_STYLES, map_style + \
                                        " (map_style parameter) is not a valid CartoDB mapping style. Options are " + \
                                        str(MAP_STYLES)
        smopy.TILE_SERVER = "http://1.basemaps.cartocdn.com/" + map_style + "/{z}/{x}/{y}.png"
    else:
        smopy.TILE_SERVER = "http://1.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"

    args = (lat_min, lat_max, lon_min, lon_max, map_style, z)
    if args not in get_smopy_map.maps:
        kwargs = {}
        if z is not None:  # this hack may not work
            smopy.Map.get_allowed_zoom = lambda self, z: z
            kwargs['z'] = z
        try:
            get_smopy_map.maps[args] = smopy.Map(
                (lat_min, lon_min, lat_max, lon_max), **kwargs)
        except URLError:
            raise RuntimeError(
                "\n Could not load background map from the tile server: " +
                smopy.TILE_SERVER +
                "\n Please check that the tile server exists and "
                "that your are connected to the internet.")
    smopy.TILE_SERVER = ORIG_TILE_SERVER
    return get_smopy_map.maps[args]
Ejemplo n.º 12
0
Archivo: api.py Proyecto: hiway/piebus
 def fetch_map(self):
     data = self.jdata
     if 'location' in data:
         lat = data['location'].get('latitude')
         lon = data['location'].get('longitude')
         map = smopy.Map(
             (lat - 0.006, lon - 0.038, lat + 0.006, lon + 0.038),
             z=12,
             tileserver=
             "http://tile.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png",
             tilesize=512,
             maxtiles=16)
         x, y = map.to_pixels(lat, lon)
         x = int(x)
         y = int(y)
         fname = f'map_{self.uuid}.png'
         map.save_png(f'content/{fname}')
         img = Image.open(open(f'content/{fname}', 'rb'))
         draw = ImageDraw.Draw(img)
         draw.ellipse([(x - 10, y - 10), (x + 10, y + 10)],
                      fill=128,
                      width=10)
         del draw
         ffname = f'content/loc_{fname}'
         img.save(ffname, "PNG")
         data.update({'media_url': ffname})
         self.data = json.dumps(data)
         self.save()
         return f'loc_{fname}'
     else:
         raise KeyError(f'No location data found in frame: {self}')
Ejemplo n.º 13
0
def GetBaseMap():
    import smopy
    # https://github.com/CartoDB/basemap-styles
    # https://github.com/CartoDB/cartodb/wiki/BaseMaps-available
    basemaps = [
        'light_all', 'dark_all', 'light_nolabels', 'light_only_labels',
        'dark_nolabels', 'dark_only_labels', 'rastertiles/voyager',
        'rastertiles/voyager_nolabels', 'rastertiles/voyager_only_labels',
        'rastertiles/voyager_labels_under'
    ]
    global mapbounds
    print("downloading basemap: " + base + '-map.png')
    lonRange = abs(bounds['maxlon'] - bounds['minlon'])
    latRange = abs(bounds['maxlat'] - bounds['minlat'])
    mapbounds['minlon'] = bounds['minlon'] - lonRange * 0.1
    mapbounds['maxlon'] = bounds['maxlon'] + lonRange * 0.1
    mapbounds['minlat'] = bounds['minlat'] - latRange * 0.1
    mapbounds['maxlat'] = bounds['maxlat'] + latRange * 0.1
    s = 'c'  # one of the available subdomains, either [a,b,c,d]
    # {z} : Zoom level. We support from 0 to 20 zoom levels in OSM tiling system.
    # {x},{y}: Tile coordinates in OSM tiling system
    scale = '@2x'  # OPTIONAL "@2x" for double resolution tiles
    smopy.TILE_SERVER = f"https://{s}.basemaps.cartocdn.com/{basemaps[2]}/{{z}}/{{x}}/{{y}}{scale}.png"
    smopy.TILE_SIZE = 512
    map = smopy.Map((mapbounds['minlat'], mapbounds['minlon'],
                     mapbounds['maxlat'], mapbounds['maxlon']),
                    z=12,
                    margin=0)
    x1, y1 = map.to_pixels(mapbounds['maxlat'], mapbounds['minlon'])
    x2, y2 = map.to_pixels(mapbounds['minlat'], mapbounds['maxlon'])
    img = map.img.crop((x1, y1, x2, y2))
    img.save(BASE + '-Map.png')
Ejemplo n.º 14
0
def add_area_points(data, zoom, area, title=None):
    longitude = data['longitude'].values
    latitude = data['latitude'].values
    count = data['count'].values
    radius = data['radius'].values

    area_lon, area_lat = str2float(area)
    Map = smopy.Map((area_lat.min(), area_lon.min(), area_lat.max(), area_lon.max()), z=zoom)

    lon = []
    lat = []
    for i in range(len(longitude)):
        m, n = gcj02_to_wgs84(longitude[i], latitude[i])
        lon.append(m)
        lat.append(n)

    lon = np.array(lon)
    lat = np.array(lat)
    x, y = Map.to_pixels(lat, lon)

    shape = [pi * r * r / 8 for r in radius]

    ax = Map.show_mpl(figsize=(8, 8))
    # cm = plt.cm.get_cmap('RdYlBu')
    ax = plt.scatter(x, y, c=count, s=shape, alpha=0.5, orientation=0)
    # plt.colorbar(ax)

    if title:
        plt.title(title)
        plt.savefig(fname=title, dpi=300)
    plt.show()
Ejemplo n.º 15
0
def get_img(IP_list_tuple, myIP):

    IP_xy = []

    for IP_tuple in IP_list_tuple:
        for i in IP_tuple:
            if not i == myIP:
                XY = get_XY(ip=i)
                if not XY == None:
                    IP_xy.append(XY)
    printWARN("+" * 100)
    mp = smopy.Map(
        (min(IP_xy)[0], min(IP_xy)[1], max(IP_xy)[0], max(IP_xy)[1]), z=5)
    x = []
    y = []
    for xy in IP_xy:
        x1, y1 = mp.to_pixels(xy[0], xy[1])
        x.append(x1)
        y.append(y1)
    printWARN("*" * 100)
    mp.save_png("unit/curmap.png")
    plt.figure()
    ax = plt.subplot(111)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.xlim(0, mp.w)
    plt.ylim(mp.h, 0)
    plt.axis('off')
    plt.tight_layout()
    ax.imshow(mp.img)
    ax.plot(x, y, 'or')
    plt.savefig("unit/plot.png")
Ejemplo n.º 16
0
def getMap(y1, x1, y2, x2):
    map = smopy.Map(
        (y1, x1, y2, x2),
        tileserver=
        "http://tile.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png",
        tilesize=512,
        maxtiles=16)
    return map
Ejemplo n.º 17
0
    def __init__(self, parent=None):
        super(MapWidget, self).__init__(parent)
        self.setFlags(self.ItemIsSelectable | self.ItemIsMovable)

        # get map
        map = smopy.Map((37, -3), z=11, tilesize=48)
        numpy_image = map.to_numpy()
        img = QImage(numpy_image.data, *numpy_image.shape[1::-1], QImage.Format_RGB888)
        self.setPixmap(QPixmap.fromImage(img))
def get_map(locations):
    area = get_area(locations)
    map = smopy.Map((area['lat_min'],area['lon_min'],area['lat_max'],area['lon_max']), z=15)
    ax = map.show_mpl(figsize=(8,8))
    for location in locations :
        x,y = map.to_pixels(float(location['lat']),float(location['lon']))
        ax.plot(x,y, 'yo', ms=5, mew=5)
    plt.show()
    return True
def map_cache(path, bounding_box):
    try:
        with open(path, 'rb') as map_file:
            map_area = pickle.load(map_file)
    except FileNotFoundError:
        print(f"Map file doesn't exist, writing to {path}. May take a moment.")
        map_area = smopy.Map(bounding_box, maxtiles=512)
        with open(path, 'wb') as map_file:
            pickle.dump(map_area, map_file, protocol=pickle.HIGHEST_PROTOCOL)
    return map_area
Ejemplo n.º 20
0
 def update_map_center_handler(self):
     new_map = smopy.Map(
         (self.mapCenterLat - mapScale[self.scaleyboi] / 2,
          self.mapCenterLong - mapScale[self.scaleyboi] / 2,
          self.mapCenterLat + mapScale[self.scaleyboi] / 2,
          self.mapCenterLong + mapScale[self.scaleyboi] / 2),
         z=self.scaleyboi,
         tileserver='http://192.168.1.152/osm_tiles/{z}/{x}/{y}.png')
     self.blank_map = new_map
     threading.Timer(10, self.update_map_center_handler).start()
Ejemplo n.º 21
0
    def __init__(self,
                 df_points,
                 dpi=100,
                 bg_map=True,
                 aspect='equal',
                 map_transparency=0.5):
        if not isinstance(df_points, list):
            df_points = [df_points]

        self.fig, self.axarr = plt.subplots(len(df_points),
                                            1,
                                            facecolor='0.05',
                                            dpi=dpi)
        if not isinstance(self.axarr, np.ndarray):
            self.axarr = [self.axarr]

        self.map = []
        self.track_df = DFTrack()
        for i in range(len(df_points)):
            df = df_points[i].get_tracks()
            df.df['Axes'] = i
            self.track_df = self.track_df.concat(df)

            trk_bounds = df.get_bounds()
            min_lat = trk_bounds.min_latitude
            max_lat = trk_bounds.max_latitude
            min_lng = trk_bounds.min_longitude
            max_lng = trk_bounds.max_longitude
            if bg_map:
                self.map.append(smopy.Map(
                    (min_lat, min_lng, max_lat, max_lng)))
                self.axarr[i].imshow(self.map[i].img,
                                     aspect=aspect,
                                     alpha=map_transparency)
            else:
                self.axarr[i].set_ylim([min_lat, max_lat])
                self.axarr[i].set_xlim([min_lng, max_lng])

            self.axarr[i].set_facecolor('0.05')
            self.axarr[i].tick_params(color='0.05', labelcolor='0.05')
            for spine in self.axarr[i].spines.values():
                spine.set_edgecolor('white')

        self.fig.tight_layout()
        plt.subplots_adjust(wspace=0.1, hspace=0.1)

        if 'VideoFrame' in self.track_df.df:
            self.track_df = self.track_df.sort(
                ['VideoFrame', 'Axes', 'CodeRoute'])
        else:
            self.track_df = self.track_df.sort(['Axes', 'Date'])

        self.track_df.df = self.track_df.df.reset_index(drop=True)
Ejemplo n.º 22
0
    def load_map(self, lowest_point, longitude, latitude):
        self.fig = plt.figure("GPS", figsize=(20, 8), dpi=300)
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)

        self.map = smopy.Map((lowest_point[1], lowest_point[0], lowest_point[1] + latitude,
                              lowest_point[0] + longitude), z=15)
        gps_in_img_coords = []
        for coord in range(self.gps_coords.shape[0]):
            x, y = self.map.to_pixels(*self.gps_coords[["GPS_Longitude", "GPS_Latitude"]].iloc[coord, :].values[::-1])
            gps_in_img_coords.append((x, y))
        self.gps_coords["longitude_img"] = np.array(gps_in_img_coords)[:, 0]
        self.gps_coords["latitude_img"] = np.array(gps_in_img_coords)[:, 1]
    def __init__(self, min_lat, max_lat, min_lon, max_lon, z=-1):
        '''
        Constructor for the class
        @param min_lat: The bounding minimum latitude
        @param max_lat: The bounding maximum latitude
        @param min_lon: The bounding minimum longitude
        @param max_lon: The bounding maximum longitude
        @param tile_x: The x location of this tile in the larger map
        @param tile_y: The y location of this tile in the larger map
        '''
        # Save the bounding values
        self._min_lat = min_lat
        self._max_lat = max_lat

        self._min_lon = min_lon
        self._max_lon = max_lon

        # Establish attributes for the u v bounds
        self._u_min = None
        self._v_min = None
        self._u_max = None
        self._v_max = None

        # Save the tile coordinates
        self._tile_x = None
        self._tile_y = None

        # Create the smopy map
        self._map = None
        self._zoom = None
        if z == -1:
            self._map = smopy.Map(
                (self._min_lat, self._min_lon, self._max_lat, self._max_lon))
            self._zoom = self._map.z
        else:
            self._zoom = z
            self._map = smopy.Map(
                (self._min_lat, self._min_lon, self._max_lat, self._max_lon),
                z=z)
        self.populate_limits_uv()
Ejemplo n.º 24
0
def get_map(locations):
    area = get_area(locations)
    map = smopy.Map( (area['lat_min'],area['lon_min'],area['lat_max'],area['lon_max']) , z=8)
    # Create a figure with the map : 
    fig, ax = plt.subplots()
    ax = map.show_mpl(figsize=(8,8))
    for index, row in locations.iterrows():
        row['x'],row['y'] = map.to_pixels(float(row['lat']),float(row['lon']))
        ax.plot(row['x'],row['y'], 'sg', ms=5)
        ax.annotate(row['temp'],xy=(row['x'],row['y']),xytext=(row['x']+5,row['y']+5))
    ax.scatter(locations.x, locations.y, c=locations.temp, s=100,vmin=locations.temp.min(), vmax=locations.temp.max())
    
    plt.show()
Ejemplo n.º 25
0
def get_map(locations):
    area = get_area(locations)
    map = smopy.Map(
        (area['lat_min'], area['lon_min'], area['lat_max'], area['lon_max']),
        z=8)
    # Create a figure with the map :
    ax = map.show_mpl(figsize=(8, 8))
    for location in locations:
        x, y = map.to_pixels(float(location['lat']), float(location['lon']))
        ax.plot(x, y, 'sg', ms=5)
        ax.annotate(location['temp'], xy=(x, y), xytext=(x + 5, y + 5))
    plt.show()
    return True
Ejemplo n.º 26
0
def get_map(locations):
    area = get_area(locations)
    map = smopy.Map(
        (area['lat_min'], area['lon_min'], area['lat_max'], area['lon_max']),
        z=6)
    # z = zoom
    # create a figure with the map :
    ax = map.show_mpl(figsize=(8, 6))
    for location in locations:
        x, y = map.to_pixels(float(location['lat']), float(location['lon']))
        ax.plot(x, y, 'ob', ms=2, mew=5)
        # ms = épaisseur & mew = diamètre des points & or = couleur
    plt.show()
    return True
Ejemplo n.º 27
0
    def plot_map(self, ts, speed, outfile):
        if self.initial_coords:
            # for whole sequences
            if True:
                lat_min = np.min(self.coordinates[:,0]) - 0.0001
                lat_max = np.max(self.coordinates[:,0]) + 0.0001

                lon_min = np.min(self.coordinates[:,1]) - 0.0001 
                lon_max = np.max(self.coordinates[:,1]) + 0.0001
            else:
                # for area around current position
                ll_lon = self.coordinates[ts,1] - 0.001
                ll_lat = self.coordinates[ts,0] - 0.001
                ur_lon = self.coordinates[ts,1] + 0.001
                ur_lat = self.coordinates[ts,0] + 0.001
            
            # get map
            try:
                mapfilename = "%f_%f_%f_%f_%d.p" % (lat_min, lon_min, lat_max, lon_max, self.zoom)

                if os.path.isfile(mapfilename):
                    print "Loading with pickle"
                    self.map = pickle.load( open(mapfilename, "rb" ) ) 
                else:
                    print "Getting map from OSM"
                    self.map = smopy.Map((lat_min, lon_min, lat_max, lon_max), z=self.zoom)
                    pickle.dump(self.map, open(mapfilename , "wb" ) )

                #self.fig_map, ax = plt.subplots(ncols=1, nrows=1, frameon=False, figsize=(20,20))

                self.fig_map = plt.figure(figsize=(10,10), frameon=False)
                ax = plt.Axes(self.fig_map, [0., 0., 1., 1.])
                ax.set_axis_off()
                self.fig_map.add_axes(ax)

                self.ax = self.map.show_mpl(ax=ax, figsize=(10,10))
                
                for i in range(0,self.coordinates.shape[0]):
                    coords = self.map.to_pixels(self.coordinates[i,0], self.coordinates[i,1])
                    self.ax.plot(coords[0], coords[1], 'bo', ms=10, markeredgecolor='b')

                cc = self.map.to_pixels(self.coordinates[ts,0], self.coordinates[ts,1])
                self.current_coord = self.ax.plot(cc[0], cc[1], 'ro', ms=12)

                # only if we do not refresh the map
                self.initial_coords = False
            except Exception,e:
                print "Exception in plot_map: ", e
Ejemplo n.º 28
0
def get_map(locations):
    area = get_area(locations)
    map = smopy.Map(
        (area['lat_min'], area['lon_min'], area['lat_max'], area['lon_max']),
        z=8)
    ax = map.show_mpl(figsize=(8, 8))
    for location in locations:
        x, y = map.to_pixels(float(location['lat']), float(location['lon']))
        ax.plot(x, y, 'or', ms=10, mew=2)
        ax.annotate(
            location['temp'],
            xy=(x, y),
            xytext=(3, 3),
            textcoords="offset points",
        )
    plt.show()
    return True
Ejemplo n.º 29
0
def main(cities):
    map = smopy.Map(southernmost_lat + 6, westermost_long, northermost_lat - 3,
                    eastermost_long - 4)

    fig, ax = plt.subplots(figsize=(20, 10))

    my_map = map.show_mpl()

    plot_capital_cities(my_map, map.to_pixels)

    cities = cities

    vertexes = get_vertexes(cities, map.to_pixels)

    plot_lines_from_vertexes(vertexes, my_map)

    ax.savefig("greedy-google.jpg", dpi=100)
Ejemplo n.º 30
0
def heat_map(longitude, latitude, bins=50, title=None):
    """
    绘制热力图
    :param longitude: 经度
    :param latitude: 纬度
    :param title: 图名
    :return:
    """
    longitude = np.array(longitude)
    latitude = np.array(latitude)
    gps_map = smopy.Map(latitude.min(), longitude.min(), latitude.max(), longitude.max())

    x_lon = gps_map.to_pixels(latitude, longitude)[1]
    y_lat = gps_map.to_pixels(latitude, longitude)[0]

    smoothing = 1
    """
    cmap = LinearSegmentedColormap.from_list('mycmap', [(0, (1, 0, 0, 0)),
                                                        (0.5, (1, 0.5, 0.5, 0.8)),
                                                        (0.75, (1, 1, 0.9, 0.8)),
                                                        (0.875, (1, 1, 1, 1)),
                                                        (1, (1, 1, 1, 1))]
                                             )
    """

    colorlist = ['#5fd9cd', '#eaf786', '#ffb5a1', '#b8ffb8', '#b8f4ff']
    cmap = LinearSegmentedColormap.from_list('mycmap',
                                             [(0, (1, 0, 0, 0)),
                                              (0.5, (1, 0.5, 0, 0.8)),
                                              (0.75, (1, 1, 0, 0.8)),
                                              (0.875, (1, 1, 1, 1)),
                                              (1, (1, 1, 1, 1))
                                              ])

    heatmap, x_edges, y_edges = np.histogram2d(x_lon, y_lat, bins=bins)
    extent = [y_edges[0], y_edges[-1], x_edges[-1], x_edges[0]]
    #logheatmap = np.log(heatmap)
    #logheatmap[np.isneginf(logheatmap)] = 0
    heatmap = ndimage.filters.gaussian_filter(heatmap, smoothing, mode='nearest')

    ax = gps_map.show_mpl(dpi=300)
    ax.imshow(heatmap, cmap=cmap, extent=extent, vmin=0, vmax=10)
    if title:
        plt.title(title)
        plt.savefig(fname=title)
    plt.show()