コード例 #1
0
 def _ll_on_message(self, mosq, obj, msg):
     data = json.loads(msg.payload)
     self._markers[msg.topic] = LatLonMarker(data['lat'], data['lon'])
     dmap = DecoratedMap(size_x=320, size_y=240)
     for m in self._markers.keys():
         dmap.add_marker(self._markers[m])
     if self.on_update is not None:
         self.on_update(dmap.generate_url())
コード例 #2
0
ファイル: mapper.py プロジェクト: andyljones/flat-scraper
def get_map_url(listings):
    dmap = DecoratedMap(size_x=640, size_y=640)
    labels = OrderedDict()
    for i, (name, (lat, lon)) in enumerate(positions(listings).items()):
        label = chr(ord('A') + i)
        labels[label] = name
        dmap.add_marker(LatLonMarker(lat, lon, label=label))
    return dmap.generate_url(), labels
コード例 #3
0
ファイル: map.py プロジェクト: tschaefer/wegweiser
 def __init__(
         self, size_x=400, size_y=400, maptype='roadmap', region=False,
         fillcolor='green', pathweight=None, pathcolor=None, filename=None):
     DecoratedMap.__init__(
             self, size_x=size_x, size_y=size_y, maptype=maptype,
             region=region, fillcolor=fillcolor, pathweight=None,
             pathcolor=None)
     self._filename = filename
     self._spots = []
コード例 #4
0
ファイル: views.py プロジェクト: loryfelnunez/roboresto
def resto_post():
    cuisine = request.form["cuisine"]
    boro = request.form.getlist("boro")
    grade = request.form.getlist("grade")
    in_grade = ','.join((str("\"" +g+ "\"") for g in grade))
    in_boro = ','.join((str("\"" +b+ "\"") for b in boro))
    print "Grade",  in_grade
    if len(in_grade) == 0:
        in_grade = "\"A\", \"B\", \"C\", \"D\""
    if len(in_boro) == 0:
        in_boro = "\"Manhattan\", \"Brooklyn\", \"Bronx\", \"Staten Island\", \"Queens\""

    sql = "SELECT distinct cuisine, dba, full_address  \
           FROM restaurant \
           JOIN inspection ON restaurant.camis = inspection.camis \
           WHERE cuisine = \"" + cuisine + "\" AND inspection.grade IN(" + in_grade + ") AND restaurant.boro IN(" + in_boro + ") \
           ORDER BY inspection.inspection_date DESC LIMIT 10"  
    print sql
    cursor.execute (sql)
    response = cursor.fetchall()

    dmap = DecoratedMap()
    count = 1
    mapped = 0
    results = []
    for r in response:
        match_result = {}
        match_result['dba'] = r[1]
        full_address = r[2]
        match_result['full_address'] = full_address 
        label_char = str(unichr(count+64))
        match_result['label_char'] =  label_char
        if full_address is not None:
            mapped = mapped + 1
            dmap.add_marker(AddressMarker(full_address,label=label_char))
        results.append(match_result)        
        count = count + 1
        print r

    if mapped > 0: 
        map_url =  dmap.generate_url()
    else:
        map_url = "../static/images/comedian-robot.jpg"

    if len(results) == 0:
       empty_result = {}
       empty_result['dba'] = "Sorry, no restos found "
       results.append(empty_result)

    jsonresponse = {}
    jsonresponse['map'] = map_url
    jsonresponse['restos'] = results
    print jsonresponse
    return render_template("resto_post.html", output=jsonresponse)
コード例 #5
0
ファイル: core.py プロジェクト: fo0nikens/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)
コード例 #6
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()
コード例 #7
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|'
     )
コード例 #8
0
ファイル: map_decode.py プロジェクト: balamark/CollabMeet
def generate_map_and_desc(gps_data,mode,marker_list):
    ischina=False
    api_key='AIzaSyBepV-5hoVd8xzwkdE93I0eRKf2jTlys3U'
    gmaps = GoogleMaps(api_key)
    gps=gps_data
    try:
        result = Geocoder.reverse_geocode(gps_data[0],gps_data[1])
        destination = str(result)
    except:
        destination = 'N/A'
    
    if mode==0:
        dmap=DecoratedMap(size_x=400,size_y=400)
    else:
        dmap=DecoratedMap(size_x=400,size_y=400, maptype='satellite')

    dmap.add_marker(LatLonMarker(lat=gps[0],lon=gps[1],label='A'))
    for i in range(0, len(marker_list)):
        dmap.add_marker(LatLonMarker(lat=marker_list[i][0],lon=marker_list[i][1],label=chr(66+i)))

    cmap = CenterMap(lat=gps[0],lon=gps[1], zoom=12)
    map_url=dmap.generate_url()
    print(map_url)
    f=open('tmp.png','wr')
    f.write(urllib.urlopen(map_url).read())
    f.close()

    return destination
コード例 #9
0
ファイル: map_decode.py プロジェクト: rpraveen/CollabMeet
def generate_map_and_desc(gps_data, marker_list):
    api_key='AIzaSyBepV-5hoVd8xzwkdE93I0eRKf2jTlys3U'
    gmaps = GoogleMaps(api_key)
    gps=gps_data
    try:
        result = Geocoder.reverse_geocode(gps_data[0],gps_data[1])
        destination = str(result)
    except:
        destination = 'N/A'
    dmap=DecoratedMap(size_x=400,size_y=400)
    for i in range(0, len(marker_list)):
        dmap.add_marker(LatLonMarker(lat=marker_list[i][0], lon=marker_list[i][1], label=marker_list[i][2]))
    cmap = CenterMap(lat=gps[0],lon=gps[1], zoom=12)
    map_url=dmap.generate_url()
    f=open(instance.name + '_map.png','wr')
    f.write(urllib.urlopen(map_url).read())
    f.close()
    return destination
コード例 #10
0
ファイル: models.py プロジェクト: dchud/bikestat
 def map_url(self):
     dmap = DecoratedMap(size_x=200, size_y=200)
     if self.station_start == self.station_end:
         dmap.add_marker(AddressMarker('%s, Washington, DC' %
                         self.station_start.desc, color='blue', label='B'))
     else:
         dmap.add_marker(AddressMarker('%s, Washington, DC' %
                         self.station_start.desc, color='green', label='S'))
         dmap.add_marker(AddressMarker('%s, Washington, DC' %
                         self.station_end.desc, color='red', label='E'))
     return dmap.generate_url()
コード例 #11
0
ファイル: biketl.py プロジェクト: rekab/biketl
def GetMapForPoints(output_dir, file_basename, points, mapdelay=3):
  # Map creation is expensive, so check if we've already fetched it.
  map_image_fname = os.path.join(output_dir, 'map-%s.png' % file_basename)
  latest = points[-1]
  if os.path.exists(map_image_fname):
    print 'map already exists for %s' % latest
    return map_image_fname

  print 'getting map for %s' % latest
  gmap = DecoratedMap(size_x=200, size_y=200, pathweight=4, pathcolor='red')
  gmap.add_marker(
      LatLonMarker(*tuple(str(x) for x in points[-1].position), color='red'))
  print 'sleeping %s seconds' % mapdelay
  time.sleep(mapdelay)
  resp = urllib2.urlopen(gmap.generate_url() + '&zoom=11')
  f = open(map_image_fname, 'w')
  f.write(resp.read())
  f.close()
  return map_image_fname
コード例 #12
0
ファイル: test_motionless.py プロジェクト: ryancox/motionless
    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='
        )
コード例 #13
0
ファイル: test_motionless.py プロジェクト: ryancox/motionless
 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.googleapis.com/maps/api/staticmap?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'
     )
コード例 #14
0
ファイル: test_motionless.py プロジェクト: ryancox/motionless
    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 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()
コード例 #16
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
コード例 #17
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'''
コード例 #18
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()
コード例 #19
0
ファイル: views.py プロジェクト: x3rus/dj_course
def extract_gpx_basic_info(gpx_file_name,original_file_name="none"):
    basic_info = {}
    basic_info['name'] = 'unknown'
    basic_info['description'] = 'unknown'
    basic_info['author'] = 'unknown'
    basic_info['email'] = 'unknown'

    gpx = mod_gpxpy.parse(open(gpx_file_name))

    if gpx.name:
        basic_info['name'] = gpx.name
    else :
        basic_info['name'] = original_file_name.rsplit('.', 1)[0]
    if gpx.description:
        basic_info['description'] = gpx.description
    if gpx.author_name:
        basic_info['author'] = gpx.author
    if gpx.author_email:
        basic_info['email'] = gpx.email

    basic_info['start_time'],basic_info['end_time'] = gpx.get_time_bounds()
    # Set value in kilometers
    basic_info['length'] = gpx.length_2d() / 1000

    moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
    basic_info['moving_time'] = moving_time

    # create URL for static image map
    static_map = DecoratedMap(size_x=640,size_y=600,pathweight=8,pathcolor='blue')
    parser = xml.sax.make_parser()
    parser.setContentHandler(GPXHandler(static_map))
    parser.feed(open(gpx_file_name).read())
    basic_info['url_map'] = static_map.generate_url()



    return basic_info
コード例 #20
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()
コード例 #21
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
コード例 #22
0
ファイル: test_motionless.py プロジェクト: exislow/motionless
    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()
コード例 #23
0
ファイル: models.py プロジェクト: dchud/bikestat
def multi_map(rides):
    contiguous = False
    bikes = set([r.bike.num for r in rides])
    if len(bikes) == 1:
        contiguous = True
    dmap = DecoratedMap(size_x=600, size_y=600)
    for i in range(len(rides)):
        ride = rides[i]
        if contiguous:
            dmap.add_marker(AddressMarker('%s, Washington, DC' %
                            ride.station_start.desc, color='white',
                            label=chr(65 + i)))
        else:
            dmap.add_marker(AddressMarker('%s, Washington, DC' %
                            ride.station_start.desc, color='green', label='S'))
            dmap.add_marker(AddressMarker('%s, Washington, DC' %
                            ride.station_end.desc, color='red', label='E'))
    return dmap.generate_url()
コード例 #24
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)
コード例 #25
0
ファイル: earthquakes.py プロジェクト: ryancox/motionless
from six.moves.urllib import request
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 = """
コード例 #26
0
ファイル: munich.py プロジェクト: dannyiland/motionless
        self.first = True 
        self.prev = None

    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'))

    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()
コード例 #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
ファイル: 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'
コード例 #29
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>
コード例 #30
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()
コード例 #31
0
ファイル: util.py プロジェクト: hoangphamw/obot
def generate_map_url(lat, lon):
    dmap = DecoratedMap()
    dmap.add_marker(LatLonMarker(lat=lat, lon=lon))
    return dmap.generate_url()
コード例 #32
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)
コード例 #33
0
#!/usr/bin/python
"""Sample code to demonstrate motionless"""

import requests
from StringIO import StringIO
from PIL import Image
from slugify import slugify
from motionless import DecoratedMap, AddressMarker

address = "70 NW Couch St, Portland, OR 97209"
# generate static map object
dmap = DecoratedMap(
    maptype='satellite', zoom=18)
dmap.add_marker(
    AddressMarker(address))

# download the static image
response = requests.get(dmap.generate_url())
if response.status_code == 200:
    image = Image.open(StringIO(response.content))
    image.save('.'.join([slugify(address), 'png']))
else:
    print ("Download error with status code %s",
           response.status_code)
コード例 #34
0
ファイル: gps_data_gui.py プロジェクト: TightSquad/HABIP
class MapWindow(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.caption = Label(self, text="Hi")
        self.caption.pack()

        self.initMap()
        self.image = ImageTk.PhotoImage(self.im)
        self.image_label = Label(self, image=self.image, bd=0)
        self.image_label.pack()
        self.pack(side="top", fill="both", expand=True)

        # Open up data log file
        self.dataFileHandle = open("/home/spex/habip_data.log", "r")
        self.dataFileHandle.seek(0, 2)  # Seek to the end of the log file

        self.latList = []
        self.lonList = []

        self.id = self.after(1000, self.mapLoop)

    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)

    def mapLoop(self):
        # Grab new command log lines
        dataLine = self.dataFileHandle.readline()
        while dataLine:
            if len(dataLine) > 1:
                dataLineParts = dataLine.split(
                    ",")  # Sensor data is comma separated

                # Grab latitude and longitude
                lat = dataLineParts[60]  # N (+) or S (-)
                lon = dataLineParts[61]  # E (+) or W (-)

                # Just continue if there is data present
                if (lat != "NULL") and (lon != "NULL"):
                    # Change latitude and longitude to be +- instead of direction
                    #if lat[-1] == "N":
                    #    lat = lat[:-1]
                    #elif lat[-1] == "S":
                    #    lat = "-" + lat[:-1]
                    #if lon[-1] == "E":
                    #    lon = lon[:-1]
                    #elif lon[-1] == "W":
                    #    lon = "-" + lon[:-1]

                    # Add latitude and longitude to lists
                    self.latList.append(lat)
                    self.lonList.append(lon)

            self.updateImage()
            dataLine = self.dataFileHandle.readline()

        self.id = self.after(
            1000, self.mapLoop
        )  # Keep checking for more data (keep re-calling this function) every 1000ms

    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)
コード例 #35
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
コード例 #36
0
ファイル: run.py プロジェクト: eelcodijkstra/teststuff
        self.first = True 
        self.prev = None

    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'))

    def endElement(self,name):
        if name == 'trk':
            self.gmap.add_marker(LatLonMarker(self.prev[0],self.prev[1],color='red',label='E'))
        
run = DecoratedMap(size_x=640,size_y=640,pathweight=8,pathcolor='blue')
parser = xml.sax.make_parser()
parser.setContentHandler(GPXHandler(run))
parser.feed(open('150328 Long run.gpx').read())

htmlPage = """
<html>
<body>
<h2>Run</h2>
<i>3/29/15 long run. 150328 Long run.gpx file from MotionX on my iphone.</i>
<p/>
<p/>
<img src="%s"/>
</body>
</html>	
""" % run.generate_url()
コード例 #37
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 = """
コード例 #38
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()