コード例 #1
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
コード例 #2
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"])
コード例 #3
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
コード例 #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 _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())
コード例 #6
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
コード例 #7
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
コード例 #8
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()
コード例 #9
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()
コード例 #10
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)
コード例 #11
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()
コード例 #12
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()
コード例 #13
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)
コード例 #14
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()
コード例 #15
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='
        )
コード例 #16
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,
    )
コード例 #17
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|'
     )
コード例 #18
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=')
コード例 #19
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
コード例 #20
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|')
コード例 #21
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
コード例 #22
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)
コード例 #23
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='
        )
コード例 #24
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'
     )
コード例 #25
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='
        )
コード例 #26
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))
コード例 #27
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
コード例 #28
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()
コード例 #29
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'''
コード例 #30
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
コード例 #31
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()
コード例 #32
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
コード例 #33
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()
コード例 #34
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)
コード例 #35
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()
コード例 #36
0
# 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()
コード例 #37
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()
コード例 #38
0
ファイル: main.py プロジェクト: GuilleHilal/ProyectoIngenia
    "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)
コード例 #39
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
コード例 #40
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)
コード例 #41
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)
コード例 #42
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()
コード例 #43
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>
コード例 #44
0
ファイル: earthquakes.py プロジェクト: ryancox/motionless
# 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()