コード例 #1
0
def add_sensor_map(layout, widget):
    if "group" not in layout: return
    sensors = utils.get_group_string(layout["group"])
    if sensors is None: return
    # setup the map
    map = DecoratedMap(maptype=conf["gui"]["maps"]["type"],
                       size_x=conf["gui"]["maps"]["size_x"],
                       size_y=conf["gui"]["maps"]["size_y"])
    for i in range(len(sensors)):
        # for each sensor of the group
        sensor = sensors[i]
        sensor_url = sensor["module_id"] + "/" + sensor[
            "group_id"] + "/" + sensor["sensor_id"]
        # retrieve the data
        markers = json.loads(
            utils.web_get(hostname + sensor_url + "/" + layout["timeframe"] +
                          "/avg"))
        if len(markers) == 0: continue
        marker = json.loads(markers[len(markers) - 1][1])
        # add the marker to the map
        map.add_marker(
            LatLonMarker(marker["latitude"],
                         marker["longitude"],
                         label=marker["label"][0].upper()))
    # download the map
    url = map.generate_url()
    r = requests.get(url, verify=False)
    save_to_file(r, widget["widget_id"])
コード例 #2
0
def create_map(center_lat, center_lon, markers):
    """Create the URL for a static google map centered in latitude
    `center_lat` and longitude `center_lon`. It shows in the map
    markers labeled with numbers in the given coordinates.


    :param center_lat: Latitude of the center of the map
    :param center_lon: Longitude of the center of the map
    :param markers: List of coordinates for the markers

    :returns: URL for static google map
    """

    google_map = DecoratedMap(lat=center_lat,
                              lon=center_lon,
                              zoom=15,
                              size_x=400,
                              size_y=400,
                              maptype='roadmap',
                              scale=1)

    for marker_index, marker in enumerate(markers, 1):
        google_map.add_marker(
            LatLonMarker(lat=marker["lat"],
                         lon=marker["lon"],
                         label=str(marker_index)))

    url = google_map.generate_url()
    return url
コード例 #3
0
    def create_map_url(self, listing):
        if not listing['gaddress'] and not listing['geotag']:
            return None

        road_styles = [{
            'feature': 'road.highway',
            'element': 'geomoetry',
            'rules': {
                'visibility': 'simplified',
                'color': '#c280e9'
            }
        }, {
            'feature': 'transit.line',
            'rules': {
                'visibility': 'simplified',
                'color': '#bababa'
            }
        }]

        dmap = DecoratedMap(style=road_styles, key=self.google_api_key)
        for marker in self.map_markers:
            dmap.add_marker(
                AddressMarker(marker['address'], label=marker['label']))

        if listing['gaddress'] and listing['map_accuracy'] <= 10:
            dmap.add_marker(
                AddressMarker(listing['gaddress'], label='1', color='blue'))
        elif listing['geotag']:
            dmap.add_marker(
                LatLonMarker(listing['geotag'][0],
                             listing['geotag'][1],
                             label='0',
                             color='blue'))

        return dmap.generate_url()
コード例 #4
0
ファイル: core.py プロジェクト: Exi666/SciPro-Project-Climvis
def get_googlemap_url(lon, lat, zoom=10):

    dmap = DecoratedMap(lat=lat, lon=lon, zoom=zoom,
                        size_x=640, size_y=640,
                        maptype='terrain', key=GOOGLE_API_KEY)
    dmap.add_marker(LatLonMarker(lat, lon))
    return dmap.generate_url()
コード例 #5
0
def getDecoratedMap(bot, update, closestParkings, data, distances):
    road_styles = [{
        'feature': 'road.highway',
        'element': 'geomoetry',
        'rules': {
            'visibility': 'simplified',
            'color': '#c280e9'
        }
    }, {
        'feature': 'transit.line',
        'rules': {
            'visibility': 'simplified',
            'color': '#bababa'
        }
    }]
    dmap = DecoratedMap(style=road_styles)
    utente = User.objects.get(chat_id=update.message.chat_id)
    lat = utente.lat
    lon = utente.lon
    dmap.add_marker(LatLonMarker(lat, lon, label='S', color='blue'))
    i = 0
    keyboard = [[], [], []]
    table = []
    for p in closestParkings:
        if "parking" in utente.lastCommand:
            dmap.add_marker(
                LatLonMarker(lat=data[p]['geometry']['coordinates'][1],
                             lon=data[p]['geometry']['coordinates'][0],
                             label=str(i + 1)))
            textButton = createDetailsButtonTextParking(data[p], i)
            row = createRowParking(data[p], distances[i], i)

        elif "chargePoint" in utente.lastCommand:
            dmap.add_marker(
                LatLonMarker(lat=data[p]['geometry']['coordinates'][1],
                             lon=data[p]['geometry']['coordinates'][0],
                             label=str(i + 1)))
            textButton = createDetailsButtonTextChargePoint(data[p], i)
            row = createRowChargePoint(data[p], distances[i], i)

        table.append(row)
        keyboard[i].append(
            InlineKeyboardButton(text=textButton,
                                 callback_data=str(p),
                                 resize_keyboard=True))
        i += 1

    url = dmap.generate_url()
    npArray = np.array(table)
    df = pd.DataFrame(npArray)
    df.columns = ['N.', 'Parking Name', 'Free Slots', 'Distance']
    ax = render_mpl_table(df, header_columns=0, col_width=1.5)
    fileName = str(update.message.chat_id) + '.png'
    plt.savefig(fileName, bbox_inches='tight')
    baseDir = settings.BASE_DIR
    picture = open(baseDir + '/' + fileName, 'rb')
    #img=urllib.request.urlopen(baseDir + '\foo.png').read()
    bot.sendPhoto(chat_id=update.message.chat_id, photo=picture)
    print(ax)
    return url, keyboard
コード例 #6
0
def build_tweet(results):
    status = []
    dmap = DecoratedMap(size_x=640, size_y=320, key=GMAPS_API_KEY)
    for result in rg.search([tuple(res) for res in results]):
        status.append(", ".join([result['name'], result['admin1'], unicode_flag(result['cc'])]))
    for result in results:
        dmap.add_marker(LatLonMarker(result[0], result[1]))
    img_url = dmap.generate_url()
    return '\n'.join(status), img_url
コード例 #7
0
    def test_addressmarker(self):

        # For some reason the url is not always same. So the test is... well.
        dmap = DecoratedMap()
        am = AddressMarker('1 Infinite Loop, Cupertino, CA', label='A')
        dmap.add_marker(am)
        am = AddressMarker('1600 Amphitheatre Parkway Mountain View, CA',
                           label='G')
        dmap.add_marker(am)
        _ = dmap.generate_url()
コード例 #8
0
def locationsPicture(origin, locationList):
    dmap = DecoratedMap()
    dmap.add_marker(LatLonMarker(origin[0], origin[1], label='A'))
    count = 1
    for location in locationList:
        dmap.add_marker(
            LatLonMarker(location["geocode"][0],
                         location["geocode"][1],
                         color="blue",
                         label=str(count)))
        count += 1
    return dmap.generate_url()
コード例 #9
0
ファイル: gps_data_gui.py プロジェクト: TightSquad/HABIP
    def initMap(self):
        self.fileName = "/home/spex/habipMapStart.jpg"

        # Generate map URL
        self.map = DecoratedMap(key="AIzaSyDzElKnTJkAewIuxuAUZJYmRfXz1mg0vYU")
        # Add marker for Meteor Lab to start at
        self.map.add_marker(LatLonMarker(lat=43.08463, lon=-77.67914))
        self.map.add_path_latlon(lat=43.08463, lon=-77.67914)
        self.requestUrl = self.map.generate_url()

        # Save image to disk
        urllib.urlretrieve(self.requestUrl, self.fileName)
        self.im = Image.open(self.fileName)
コード例 #10
0
def create_twitter_map(coordinates):
    dmap = DecoratedMap()

    for coordinate in coordinates:
        if coordinate is None:
            continue

        lon = coordinate[0]
        lat = coordinate[1]

        tweet_marker = LatLonMarker(lat=lat, lon=lon)
        dmap.add_marker(tweet_marker)

    return dmap.generate_url()
コード例 #11
0
    def test_channel(self):
        cmap = CenterMap(lat=48.858278,
                         lon=2.294489,
                         maptype='satellite',
                         clientid='gme-exampleid',
                         secret='bbXgwW0k3631Bl2V5Z34gs9vYgf=',
                         channel='somechannel')
        self.assertEqual(
            cmap.generate_url(),
            'https://maps.googleapis.com/maps/api/staticmap?client=gme-exampleid&maptype=satellite&'
            'format=png&scale=1&center=48.858278%2C2.294489&zoom=17&'
            'size=400x400&sensor=false&language=en&channel=somechannel&'
            'signature=Y-D-iEMbWPfUTjBtKEYDbGUtElY=')

        vmap = VisibleMap(maptype='terrain',
                          clientid='gme-exampleid',
                          secret='bbXgwW0k3631Bl2V5Z34gs9vYgf=',
                          channel='somechannel')
        vmap.add_address('Sugarbowl, Truckee, CA')
        vmap.add_address('Tahoe City, CA')

        self.assertEqual(
            vmap.generate_url(),
            'https://maps.googleapis.com/maps/api/staticmap?client=gme-exampleid&maptype=terrain&'
            'format=png&scale=1&size=400x400&sensor=false&'
            'visible=Sugarbowl%2C%20Truckee%2C%20CA%7CTahoe%20City%2C%20CA&'
            'language=en&channel=somechannel&signature=KQvz4Q3rB6Pmr7sJ_sM4qfKQzDo='
        )

        styles = [{
            'feature': 'road.highway',
            'element': 'geomoetry',
            'rules': {
                'color': '#c280e9'
            }
        }]
        decorated_map = DecoratedMap(style=styles,
                                     clientid='gme-exampleid',
                                     secret='bbXgwW0k3631Bl2V5Z34gs9vYgf=',
                                     channel='somechannel')
        decorated_map.add_marker(
            LatLonMarker('37.422782', '-122.085099', label='G'))
        self.assertEqual(
            decorated_map.generate_url(),
            'https://maps.googleapis.com/maps/api/staticmap?client=gme-exampleid&maptype=roadmap&'
            'format=png&scale=1&size=400x400&sensor=false&language=en&'
            'markers=%7Clabel%3AG%7C37.422782%2C-122.085099&'
            'style=feature%3Aroad.highway%7Celement%3Ageomoetry%7C'
            'color%3A0xc280e9%7C&channel=somechannel&signature=IPHCEq1ifL7Chuwu604pMtN6eGw='
        )
コード例 #12
0
ファイル: routes.py プロジェクト: nsaritzky/greenamer
def rules():
    form = RuleForm()
    delete_forms = {
        rule.id: DeleteForm(obj=rule)
        for rule in current_user.rules
    }

    map_images = {}
    for rule in current_user.rules:
        dmap = DecoratedMap(key=Config.GOOGLEMAPS_KEY, size_x=280, size_y=280)
        dmap.add_marker(LatLonMarker(rule.lat, rule.lng))
        map_images[rule.id] = dmap.generate_url()

    # This is a hack to get the delete buttons to ignore submission of new rule forms.
    # It is inelegant.
    if form.errors is not {}:
        current_app.logger.info(form.errors)
    if form.validate_on_submit():
        for rule in current_user.rules:
            delete_forms[rule.id].id.data = None
        rule_day = timedelta(days=form.days.data)
        rule_time = form.time.data
        new_rule = current_user.make_rule(
            form.location.data,
            form.latitude.data,
            form.longitude.data,
            datetime.combine((ARBITRARY_MONDAY + rule_day), rule_time),
            form.activity_name.data,
        )
        new_rule.record()
        current_app.logger.debug("Rule form validated")
        return redirect("/index")

    if DeleteForm().validate_on_submit():
        rule = Rule.query.get(DeleteForm().id.data)
        rule.delete_rule()
        return redirect(url_for("main.rules"))

    flash_errors(form)

    return render_template(
        "rules.html",
        title="Rules",
        form=form,
        delete_forms=delete_forms,
        map_urls=map_images,
        maps_key=Config.GOOGLEMAPS_KEY,
    )
コード例 #13
0
ファイル: gps_data_gui.py プロジェクト: TightSquad/HABIP
    def updateImage(self):
        self.fileName = "/home/spex/habipMapUpdated.jpg"

        # Generate map URL
        self.map = DecoratedMap(key="AIzaSyDzElKnTJkAewIuxuAUZJYmRfXz1mg0vYU")
        for lat, lon in zip(self.latList, self.lonList):
            self.map.add_marker(LatLonMarker(lat=lat, lon=lon))
            self.map.add_path_latlon(lat=lat, lon=lon)
        self.requestUrl = self.map.generate_url()

        # Save image to disk
        urllib.urlretrieve(self.requestUrl, self.fileName)

        self.im.close()
        self.im = Image.open(self.fileName)
        self.image = ImageTk.PhotoImage(self.im)
        self.image_label.configure(image=self.image)
コード例 #14
0
    def test_client_id_and_private_key(self):
        cmap = CenterMap(lat=48.858278,
                         lon=2.294489,
                         maptype='satellite',
                         clientid='gme-exampleid',
                         secret='bbXgwW0k3631Bl2V5Z34gs9vYgf=')
        self.assertEqual(
            cmap.generate_url(),
            'https://maps.googleapis.com/maps/api/staticmap?client=gme-exampleid&maptype=satellite&'
            'format=png&scale=1&center=48.858278%2C2.294489&zoom=17&'
            'size=400x400&sensor=false&language=en&'
            'signature=PsD-OrvyjeIflTpH1p6v5hElJrE=')

        vmap = VisibleMap(maptype='terrain',
                          clientid='gme-exampleid',
                          secret='bbXgwW0k3631Bl2V5Z34gs9vYgf=')
        vmap.add_address('Sugarbowl, Truckee, CA')
        vmap.add_address('Tahoe City, CA')

        self.assertEqual(
            vmap.generate_url(),
            'https://maps.googleapis.com/maps/api/staticmap?client=gme-exampleid&maptype=terrain&'
            'format=png&scale=1&size=400x400&sensor=false&'
            'visible=Sugarbowl%2C%20Truckee%2C%20CA%7CTahoe%20City%2C%20CA&'
            'language=en&signature=0_hfvOReb4YQfq7sGyAs0dLEDEo=')

        styles = [{
            'feature': 'road.highway',
            'element': 'geomoetry',
            'rules': {
                'color': '#c280e9'
            }
        }]
        decorated_map = DecoratedMap(style=styles,
                                     clientid='gme-exampleid',
                                     secret='bbXgwW0k3631Bl2V5Z34gs9vYgf=')
        decorated_map.add_marker(
            LatLonMarker('37.422782', '-122.085099', label='G'))
        self.assertEqual(
            decorated_map.generate_url(),
            'https://maps.googleapis.com/maps/api/staticmap?client=gme-exampleid&maptype=roadmap&'
            'format=png&scale=1&size=400x400&sensor=false&language=en&'
            'markers=%7Clabel%3AG%7C37.422782%2C-122.085099&'
            'style=feature%3Aroad.highway%7Celement%3Ageomoetry%7C'
            'color%3A0xc280e9%7C&signature=bkshPe4g0vRn1Wt3n-rUZvEEN4M=')
コード例 #15
0
 def test_create_marker_map_with_styles(self):
     """Check correct url generated with markers + styles"""
     styles = [{
         'feature': 'road.highway',
         'element': 'geomoetry',
         'rules': {
             'color': '#c280e9'
         }
     }]
     decorated_map = DecoratedMap(style=styles)
     decorated_map.add_marker(
         LatLonMarker('37.422782', '-122.085099', label='G'))
     self.assertEqual(
         decorated_map.generate_url(),
         'https://maps.google.com/maps/api/staticmap?maptype=roadmap&'
         'format=png&scale=1&size=400x400&sensor=false&language=en&'
         'markers=|label:G|37.422782,-122.085099&'
         'style=feature:road.highway|element:geomoetry|color:0xc280e9|')
コード例 #16
0
ファイル: core.py プロジェクト: lyusupov/Argus
def Map(dlist, dlock):
    "Create a Google map of traffic."
    while True:
        dmap = DecoratedMap(maptype='hybrid', size_x=640, size_y=640)
        dlock.acquire()
        ndx = len(dlist)
        for element in dlist:
            i = dlist.index(element)
            label = Marker.LABELS[i]
            dmap.add_marker(
                LatLonMarker(element.lat,
                             element.lgt,
                             color='red',
                             size='mid',
                             label=label))
        dlock.release()
        if ndx > 0:
            print dmap.generate_url()
        time.sleep(MAP_CYCLE)
コード例 #17
0
def static_map_url(markers, zoom=None):
    key = 'AIzaSyDpT6xnePrW02hH4XxErpTf1OV2yRu4RbQ'

    road_styles = [{
        'feature': 'road.highway',
        'element': 'geometry',
        'rules': {
            'visibility': 'simplified',
            'color': '#c280e9'
        }
    }, {
        'feature': 'transit.line',
        'rules': {
            'visibility': 'simplified',
            'color': '#bababa'
        }
    }]
    dmap = DecoratedMap(style=road_styles, zoom=zoom)
    for i, (latitude, longitude) in enumerate(markers):
        dmap.add_marker(LatLonMarker(latitude, longitude, label=chr(65 + i)))
    return (dmap.generate_url() + '&key={}'.format(key))
コード例 #18
0
def get_googlemap_track_url(gpx_file_path, lat_centre, lon_centre, zoom=10):
    """
    fuction that generates the url to plot the user .gpx tour on a map

    Parameters
    -------------
    gpx_file_path: string
        is the file path to the .gpx file

    lat_centre: float
        the latitude of the centre of the displayed map

    lon_centre: float
        the longitude of the  centre of the displayed map

    zoom: int, optional
        default value = 10, sets the enlargement of the map

    """

    # gets the map around the spacified coordinates and sets default size and type
    dmap = DecoratedMap(lat=lat_centre,
                        lon=lon_centre,
                        zoom=zoom,
                        size_x=640,
                        size_y=640,
                        maptype='terrain',
                        key=GOOGLE_API_KEY)

    # create xml.sax parser object named 'parser' and set GPXHandler()
    # previously defined as its'default contenthandler
    parser = xml.sax.make_parser()
    parser.setContentHandler(GPXHandler(dmap))

    # go to user input .gpx file and read it
    with open(gpx_file_path) as f:
        parser.feed(f.read())

    # generate url for dmap, default method from motionless
    return dmap.generate_url()
コード例 #19
0
def pictureUrlForRoute(polyLine, markerList):
    road_styles = [{
        'feature': 'road.highway',
        'element': 'geomoetry',
        'rules': {
            'visibility': 'simplified',
            'color': '#c280e9'
        }
    }, {
        'feature': 'transit.line',
        'rules': {
            'visibility': 'simplified',
            'color': '#bababa'
        }
    }]
    dmap = DecoratedMap(style=road_styles)
    for index, point in enumerate(markerList):
        if (len(point) == 3):
            dmap.add_marker(
                LatLonMarker(point[0],
                             point[1],
                             size="tiny",
                             icon_url="http:" + str(point[2])))
        else:
            if index == len(markerList) - 1:
                dmap.add_marker(LatLonMarker(point[0], point[1], label='B'))
            elif index == 0:
                dmap.add_marker(LatLonMarker(point[0], point[1], label='A'))
            else:
                dmap.add_marker(
                    LatLonMarker(point[0],
                                 point[1],
                                 size="small",
                                 color="blue"))
    # dmap.add_marker(LatLonMarker(origin[0], origin[1],label='A'))
    # dmap.add_marker(LatLonMarker(destination[0], destination[1],label='B'))
    dmap.add_path_latlon(46.7623430, 23.5575370)
    dmap.add_path_latlon(46.7765820, 23.6037750)
    return handlePictureUrl(dmap.generate_url(), polyLine)
コード例 #20
0
ファイル: maps.py プロジェクト: utyman/tp2-redes
def obtenerMapa(latLongs):
    """Obtener un mapa con las localizaciones
    """
    camino = []

    indice = 1
    dmap = DecoratedMap(scale=4)
    for latLong in latLongs:
        if latLong == 0:
            continue

        if latLong == None:
            indice = indice + 1
            continue
        info = latLong.split(",")
        dmap.add_marker(LatLonMarker(info[0], info[1]))
        camino.append((float(info[0]), float(info[1])))
        indice = indice + 1

    enc = polyline.encode(camino, 5)

    return dmap.generate_url() + '&path=weight:3%7Ccolor:orange%7Cenc:' + enc
コード例 #21
0
    def GetMap(self, address, key):  
        road_styles = [{
        'feature': 'road.highway',
        'element': 'geomoetry',
        'rules': {
            'visibility': 'simplified',
            'color': '#c280e9'
            }
        }, {
            'feature': 'transit.line',
            'rules': {
                'visibility': 'simplified',
                'color': '#bababa'
            }
        }]

        cmap = DecoratedMap(style = road_styles, key=key)
        cmap.add_marker(AddressMarker(address,label='A'))
        url = cmap.generate_url()
        response = requests.get(url)
        img = Image.open(BytesIO(response.content))  
		
        # 儲存圖片到Github,再下載圖片,丟到下一頁(ResultPage)
        # 可先用自己的電腦試試
        img.save(sys.path[0] + '/image/mymap.gif')
        self.img_map = tk.PhotoImage(file = sys.path[0] + '/image/mymap.gif')  
        self.lable_map = tk.Label(self.controller.get_page('Resultpage'), image = self.img_map)
        self.lable_map.place(x = 54, y = 80, anchor = 'nw')			
		
        # 測試用
        # img.show()	

        # (捨棄)另法,直接放圖片 >> 出不來,但可以再試試	
        # img = ImageTk.PhotoImage(img)
        # panel = tk.Label(self.controller.get_page('ResultPage'), image=img)
        # panel.place(x = 54, y = 80, anchor = 'nw')	

		
        '''import 外部函數 cal_point'''
コード例 #22
0
ファイル: cluster.py プロジェクト: cmcg513/cluster-routing
def generate_map_url(addresses, cluster_map, cluster_num):
    """
    Given a cluster, generate a static Google Maps image with a pin for each 
    address

    Returns the URL to this static image
    """
    # get the subset of addresses
    sa = []
    for i in range(len(addresses)):
        if cluster_map[i] == cluster_num:
            sa.append(addresses[i])

    # styling for map
    road_styles = [{
        'feature': 'road.highway',
        'element': 'geomoetry',
        'rules': {
            'visibility': 'simplified',
            'color': '#c280e9'
        }
    }, {
        'feature': 'transit.line',
        'rules': {
            'visibility': 'simplified',
            'color': '#bababa'
        }
    }]

    # get maps
    dmap = DecoratedMap(style=road_styles)

    # add marker for each address
    for a in sa:
        dmap.add_marker(AddressMarker(a))

    return dmap.generate_url()
コード例 #23
0
def createMap(coords):
    lat = coords[0]
    lng = coords[1]

    #create style for displayed map
    road_styles = [{
        'feature': 'road.highway',
        'element': 'geomoetry',
        'rules': {
            'visibility': 'simplified',
            'color': '#c280e9'
        }
    }, {
        'feature': 'transit.line',
        'rules': {
            'visibility': 'simplified',
            'color': '#bababa'
        }
    }]
    dmap = DecoratedMap(style=road_styles, key=GMAPSKEY)

    dmap.add_marker(LatLonMarker(lat, lng))
    url = dmap.generate_url()
    return url
コード例 #24
0
try:
    import geojson
except ImportError:
    print('This example requires the geojson package')
    quit()

# Get the geojson feed from USGS
opener = request.urlopen('http://earthquake.usgs.gov/earthquakes/feed/v1.0'
                         '/summary/2.5_day.geojson')

# Parse it
gjs = geojson.loads(opener.read().decode('utf-8'))

# Prepare a map and add the points
gmap = DecoratedMap(size_x=640, size_y=440)
for feat in gjs.features[:260]:  # in case there are many earthquakes today
    magnitude = feat['properties']['mag']
    lon, lat, _ = feat['geometry']["coordinates"]
    if magnitude > 2:
        color = 'yellow'
        size = 'small'
    if magnitude > 5:
        color = 'orange'
        size = 'small'
    if magnitude > 7:
        color = 'red'
        size = 'mid'
    gmap.add_marker(LatLonMarker(lat, lon, color=color, size=size))

htmlPage = """
コード例 #25
0
ファイル: main.py プロジェクト: GuilleHilal/ProyectoIngenia
    }
}, {
    'feature': 'transit',
    "element": "labels.text",
    "rules": {
        "visibility": "off"
    }
}, {
    'feature': 'administrative',
    "element": "labels.text",
    "rules": {
        "visibility": "off"
    }
}]

dmap = DecoratedMap(style=road_styles, maptype='roadmap', zoom=15, key=None)

#Agrego los marcadores
dmap.add_marker(LatLonMarker(latorigen, longorigen, label='O', color='blue'))
dmap.add_marker(LatLonMarker(latdestino, londestino, label='D'))

#Genero la URL desde donde se descarga la imagen...
url = dmap.generate_url()

#Creo la imagen...
f = open('estatico.png', 'wb')
f.write(requests.get(url).content)
f.close()

# Abrir imagen (por ahora van a ser dos tareas separadas)
imagen = 'estatico.png'
コード例 #26
0
    def getMapImage(self,
                    currentLocation,
                    missionLocations,
                    mapName='location',
                    showMap=False):
        """Use the static maps API, add the waypoints to the map as markers,
        and return the image.
        """
        if currentLocation[0] != 0 or currentLocation[1] != 0:
            print 'Current location is initialized:'
            print 'Lat:', currentLocation[0], 'Lon:', currentLocation[1]
            coor1 = round(currentLocation[0], 4)
            coor2 = round(currentLocation[1], 4)

            dmap = DecoratedMap(lat=coor1,
                                lon=coor2,
                                size_x=self.__sizeX,
                                size_y=self.__sizeY,
                                zoom=self.__zoom,
                                maptype=self.__mapType)

            marker = LatLonMarker(lat=coor1,
                                  lon=coor2,
                                  color='green',
                                  label='P')
            print 'Drawing waypoint position (P):', (coor1, coor2), '(green).'
            dmap.add_marker(marker)
        else:
            print 'Current location is uninitialized:'
            location = missionLocations[0]
            coor1 = round(location[0], 4)
            coor2 = round(location[1], 4)
            dmap = DecoratedMap(lat=coor1,
                                lon=coor2,
                                size_x=self.__sizeX,
                                size_y=self.__sizeY,
                                zoom=self.__zoom,
                                maptype=self.__mapType)
        index = 1
        for location in missionLocations:
            coor1 = round(location[0], 4)
            coor2 = round(location[1], 4)
            print 'Lat:', coor1, 'Lon:', coor2
            if location[2] == 'waypoint':
                print 'Drawing waypoint marker:', index, '(blue).'
                color = 'blue'
            elif location[2] == 'target':
                print 'Drawing target marker:', index, '(red).'
                color = 'red'
            else:
                print 'Drawing other marker:', index, '(green).'
                color = 'green'
            label = str(index)
            index += 1
            marker = LatLonMarker(lat=coor1,
                                  lon=coor2,
                                  color=color,
                                  label=label)
            dmap.add_marker(marker)

        imageFileName = mapName + ".png"
        url = dmap.generate_url()
        print url
        urllib.urlretrieve(url, imageFileName)
        # Load an color image in grayscale
        img = cv2.imread(imageFileName, cv2.IMREAD_COLOR)

        if showMap:
            plt.clf()
            # cmap = 'gray', # TODO: figure out what color map to use.
            plt.imshow(img, interpolation='bicubic')
            plt.show()
            plt.draw()
        #cv2.destroyAllWindows()
        return img
コード例 #27
0
                self.color = 'orange'
                self.size = 'small'
            if magnitude in ['7','8','9']:
                self.color = 'red'
                self.size = 'mid'

        if qname == self.qname_entry:
            self.gmap.add_marker(LatLonMarker(self.tokens[0],self.tokens[1],color=self.color,size=self.size))

        self.content = []

    def characters(self, ch):
        if self.capture:
            self.content.append(ch)

quake = DecoratedMap(size_x=640,size_y=440)
parser = xml.sax.make_parser()
parser.setContentHandler(QuakeHandler(quake))
parser.setFeature(xml.sax.handler.feature_namespaces, 1)

opener = urllib2.urlopen( 'http://earthquake.usgs.gov/earthquakes/catalogs/1day-M2.5.xml')
parser.feed(opener.read())

htmlPage = """
<html>
<body>
<h2>Earthquakes 2.5+ today</h2>
<i>GeoRSS feed parsed and visualized. Colors assigned to markers based on magnitued. Details can be found on <a href='http://earthquake.usgs.gov/earthquakes/catalogs/'>USGS web site</a>.
<p/>
<p/>
<img src="%s"/>
コード例 #28
0
"""Examples of the various maps that can be created with motionless."""
from __future__ import print_function
from motionless import AddressMarker, DecoratedMap, CenterMap, VisibleMap

cmap = CenterMap(address='151 third st, san francisco, ca')

cmap_sat = CenterMap(lat=48.858278, lon=2.294489, maptype='satellite')

vmap = VisibleMap(maptype='terrain')
vmap.add_address('Sugarbowl, Truckee, CA')
vmap.add_address('Tahoe City, CA')

dmap = DecoratedMap()
dmap.add_marker(AddressMarker('1 Infinite Loop, Cupertino, CA', label='A'))
dmap.add_marker(AddressMarker('1600 Amphitheatre Parkway Mountain View, CA',
                              label='G'))


htmlPage = """
<html>
<body>
<h2>SFMOMA</h2>
<img src="%s"/>
<h2>La Tour Eiffel</h2>
<img src="%s"/>
<h2>Tahoe City and Sugarbowl</h2>
<img src="%s"/>
<h2>Google and Apple</h2>
<img src="%s"/>
</body>
</html>
コード例 #29
0
ファイル: munich.py プロジェクト: r-dmv/motionless
                self.gmap.add_marker(
                    LatLonMarker(attrs['lat'],
                                 attrs['lon'],
                                 color='green',
                                 label='S'))

    def endElement(self, name):
        if name == 'trk':
            self.gmap.add_marker(
                LatLonMarker(self.prev[0],
                             self.prev[1],
                             color='red',
                             label='E'))


munich = DecoratedMap(size_x=640, size_y=640, pathweight=8, pathcolor='blue')
parser = xml.sax.make_parser()
parser.setContentHandler(GPXHandler(munich))
parser.feed(open('Current.gpx').read())

htmlPage = """
<html>
<body>
<h2>Munich</h2>
<i>Trip from Schwabing (S) to Airport (E). Current.gpx file taken of my Garmin device and edited down to single track.</i>
<p/>
<p/>
<img src="%s"/>
</body>
</html>	
""" % munich.generate_url()
コード例 #30
0
ファイル: lakeator.py プロジェクト: alexW335/lakeator
    def estimate_DOA_path(self,
                          method,
                          path=lambda x:
                          (np.cos(2 * np.pi * x), np.sin(2 * np.pi * x)),
                          array_GPS=False,
                          npoints=2500,
                          map_zoom=20,
                          map_scale=2,
                          freq=False,
                          AF_freqs=(False, False)):
        """Gives an estimate of the source DOA along the `path` provided, otherwise along the unit circle if `path` is not present. 

        Parameters
        ----------
        method : str 
            One of; "GCC", "MUSIC", or "AF-MUSIC". The method to use for DOA estimation.
        path : str/function 
            A filepath to a saved Google Earth path (in .kmz form), else a function f: [0,1]->R^2 to act as a parametrisation of the path at which to evaluate the DOA estimator.
        npoints : int 
            The number of points along the path to sample.
        array_GPS : ()
            !! REQUIRES CONVERSION TO PYPROJ !!
        map_zoom : int
            Zoom level of GEarth imagery. See motionless documentation for more details.
        map_scale : int
            Map scale of GEarth imagery. See motionless documentation for more details. 
        freq : float
            The frequency at which to evaluate the *narrowband* MUSIC algorithm, if using.
        AF_freqs : (float, float)
            A lower and upper limit on the frequncies at which to eveluate the AF-MUSIC algorithm, if using.
        """
        pathstr = False
        if isinstance(path, str):
            assert array_GPS
            pathstr = path
            path = self._get_path(path, array_GPS)
        else:
            assert callable(path)

        dom = np.array(path(np.linspace(0, 1, npoints)))

        if method.upper() == "GCC":
            eval_dom = self._objective_(dom[0, :], dom[1, :])
        elif method.upper() == "MUSIC":
            assert freq, "Frequency must be provided for MUSIC calculation"
            pos = fft_pack.rfftfreq(2 * self.data.shape[0]) * self.sample_rate
            actidx = np.argmin(abs(pos - freq))
            self.dataFFT = fft_pack.rfft(self.data,
                                         axis=0,
                                         n=2 * self.data.shape[0])
            eval_dom = self._MUSIC2D_((pos[actidx], actidx), dom[0:1, :].T,
                                      dom[1:, :].T).flatten()
        elif method.upper() == "AF-MUSIC" or method.upper() == "AF_MUSIC":
            self.dataFFT = fft_pack.rfft(self.data,
                                         axis=0,
                                         n=2 * self.data.shape[0])
            eval_dom = self._AF_MUSIC_subset(dom[0:1, :].T,
                                             dom[1:, :].T,
                                             freqs=AF_freqs).flatten()
        else:
            print("Method not recognised. Defaulting to GCC.")
            eval_dom = self._objective_(dom[0, :], dom[1, :])

        maxidx = np.argmax(eval_dom)
        x_max = dom[0, maxidx]
        y_max = dom[1, maxidx]
        theta = np.arctan2(y_max, x_max) * 180 / np.pi

        plt.figure(1)
        if pathstr:
            plt.subplot(121)
        else:
            pass

        p = plt.scatter(dom[0, :], dom[1, :], c=eval_dom)
        for m in np.arange(self.mics.shape[0]):
            plt.scatter(self.mics[m, 0], self.mics[m, 1], marker='x')
        plt.xlim([np.min(dom[0, :]), np.max(dom[0, :])])
        plt.ylim([np.min(dom[1, :]), np.max(dom[1, :])])
        plt.title(
            r"{} DOA Estimate; Max at $({:.2f}, {:.2f})$, $\theta={:.1f}^\circ$"
            .format(pathstr if pathstr else "", x_max, y_max, theta))
        plt.xlabel(r"x [m] East/West")
        plt.ylabel(r"y [m] North/South")
        plt.colorbar(p)

        if pathstr:
            lat, lon = _inv_proj(dom[:, maxidx:maxidx + 1].T, array_GPS)
            # print(lat, lon, '\n', array_GPS)
            with open("./data/apikey", 'r') as f_ap:
                key = f_ap.readline()
            dmap = DecoratedMap(maptype='satellite',
                                key=key,
                                zoom=map_zoom,
                                scale=map_scale)
            dmap.add_marker(
                LatLonMarker(lat=array_GPS[1], lon=array_GPS[0], label='A'))
            dmap.add_marker(LatLonMarker(lat=lat[0], lon=lon[0], label='B'))
            response = requests.get(dmap.generate_url())
            with open("{}.png".format(pathstr), 'wb') as outfile:
                outfile.write(response.content)
            im = mpimg.imread("{}.png".format(pathstr))
            plt.subplot(122)
            plt.imshow(im)
            plt.xticks([])
            plt.yticks([])
            plt.title("{} Satellite Imagery".format(pathstr))
            plt.xlabel("A: Array\nB: Bird")

        plt.show()