Exemple #1
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
Exemple #2
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()
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()
Exemple #4
0
    def startElement(self, name, attrs):
        """
        function that appends the lat and lon coordinates of the trackpoints "trkpt" in the .gps file to the list self.gmap.path
        (add_path_latlon is a method of the class DecoratedMap)
        self.gmap.path is then list of string elements ['lat1,lon1', 'lat2, lon2', ...]

        it also sets self.prev elements to be the lat and lon values last read by the if loop

        lastly, it produces a marker on gmap for the first trackpoint

        Parameters
        ----------
        name : string
            per default, in .gpx files trakpoints are indicated with 'trkpt', this allows the parser to recognize them
        attrs : xml.sax.xmlreader.AttributesImpl
            dictionary like object representing per default in xml.sax startElement() call attributes
            must be instantiated by readers, substantially contains a mappinf from attribute names (eg. 'lat') to their values

        Returns
        -------
        None.

        """

        if name == 'trkpt':
            self.gmap.add_path_latlon(attrs['lat'], attrs['lon'])
            self.prev = (attrs['lat'], attrs['lon'])

            if self.first:
                self.first = False
                marker = LatLonMarker(attrs['lat'],
                                      attrs['lon'],
                                      color='green',
                                      label='S')
                self.gmap.add_marker(marker)
Exemple #5
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"])
Exemple #6
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
Exemple #7
0
 def endElement(self, name):
     if name == 'trk':
         self.gmap.add_marker(
             LatLonMarker(self.prev[0],
                          self.prev[1],
                          color='red',
                          label='E'))
Exemple #8
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()
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
Exemple #10
0
 def startElement(self, name, attrs):
     if name == 'trkpt':
         self.gmap.add_path_latlon(attrs['lat'], attrs['lon'])
         self.prev = (attrs['lat'], attrs['lon'])
         if self.first:
             self.first = False
             self.gmap.add_marker(
                 LatLonMarker(attrs['lat'],
                              attrs['lon'],
                              color='green',
                              label='S'))
Exemple #11
0
    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)
Exemple #12
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)
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()
Exemple #14
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='
        )
Exemple #15
0
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,
    )
Exemple #16
0
    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)
Exemple #17
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=')
 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|')
Exemple #19
0
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)
Exemple #20
0
    def endElement(self, name):
        """
        function that creates the end marker for the last point in the .gps track

        Parameters
        ----------
        name : string
            per default, in .gpx files the track finishes with 'trk', this allows the parser to recognize the end of the track

        Returns
        -------
        None.

        """
        if name == 'trk':
            marker = LatLonMarker(self.prev[0],
                                  self.prev[1],
                                  color='red',
                                  label='E')
            self.gmap.add_marker(marker)
Exemple #21
0
    def endElementNS(self, qname, name):
        element = ''.join(self.content)
        if qname == self.qname_point:
            self.tokens = element.split()
        if qname == self.qname_title:
            element = ''.join(self.content)
            magnitude = element[2]
            if magnitude in ['2','3','4']:
                self.color = 'yellow'
                self.size = 'small'
            if magnitude in ['5','6']:
                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 = []
Exemple #22
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))
Exemple #23
0
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
Exemple #24
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
# 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 = """
<html>
<body>
<h2>Earthquakes 2.5+ today</h2>
<i>GeoRSS feed parsed and visualized. Colors assigned to markers based on
magnitudes. Details can be found on the
<a href='http://earthquake.usgs.gov/earthquakes/'>USGS web site</a>.
<p/>
<p/>
<img src="%s"/>
</body>
</html>
""" % gmap.generate_url()
    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
Exemple #27
0
    "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'
m_imagen = misc.imread(imagen)
m_plan = np.zeros((len(m_imagen[0]), len(m_imagen)))
print len(m_imagen)
Exemple #28
0
    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()
Exemple #29
0
def generate_map_url(lat, lon):
    dmap = DecoratedMap()
    dmap.add_marker(LatLonMarker(lat=lat, lon=lon))
    return dmap.generate_url()