def addAntPaths(self, lines, popups=None, tooltips=None, labels=None): ''' Expects list of lines. Each line is a numpy array of Nx2, with col 0: lat, col 1: lon. ''' # if the extras are none then they are all none if popups is None: popups = [None for i in lines] if tooltips is None: tooltips = [None for i in lines] if labels is None: labels = ['Trajectory ' + str(i + 1) for i in range(len(lines))] for i in range(len(lines)): line = lines[i] popup = popups[i] tooltip = tooltips[i] antpath = fop.AntPath(line, popup, tooltip) # make a new feature group fg = fo.FeatureGroup(labels[i]) antpath.add_to(fg) self.antPathLayers.append(fg) # add the feature group to the map self.antPathLayers[-1].add_to(self.map)
def test_antpath(): m = folium.Map([20., 0.], zoom_start=3) locations = [[59.355600, -31.99219], [55.178870, -42.89062], [47.754100, -43.94531], [38.272690, -37.96875], [27.059130, -41.13281], [16.299050, -36.56250], [8.4071700, -30.23437], [1.0546300, -22.50000], [-8.754790, -18.28125], [-21.61658, -20.03906], [-31.35364, -24.25781], [-39.90974, -30.93750], [-43.83453, -41.13281], [-47.75410, -49.92187], [-50.95843, -54.14062], [-55.97380, -56.60156]] antpath = plugins.AntPath(locations=locations) antpath.add_to(m) out = m._parent.render() # We verify that the script import is present. script = '<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/leaflet-ant-path.min.js"></script>' # noqa assert script in out # We verify that the script part is correct. tmpl = Template(""" {{this.get_name()}} = L.polyline.antPath( {{ this.locations|tojson }}, {{ this.options|tojson }} ) .addTo({{this._parent.get_name()}}); """) # noqa expected_rendered = tmpl.render(this=antpath) rendered = antpath._template.module.script(antpath) assert normalize(expected_rendered) == normalize(rendered)
def plot_path(pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude): ''' This function will draw a line on map btw pick-up point and drop-off point. ''' ## Use geocoder to get coodinates from address. pick_up = [pickup_latitude, pickup_longitude] drop_off = [dropoff_latitude, dropoff_longitude] route = [pick_up, drop_off] loc = list((np.array(pick_up) + np.array(drop_off)) / 2) ## base map m = folium.Map(loc) ## Draw two markers folium.Marker(pick_up, popup=f"<i>Pickup Point</i>", tootip="Click me!", icon=folium.Icon(color="blue", icon="street-view", prefix="fa")).add_to(m) folium.Marker(drop_off, popup=f"<i>Dropoff Point</i>", tootip="Click me!", icon=folium.Icon(color="lightred", icon="map-marker", prefix="fa")).add_to(m) ## Draw a Route btw two points plugins.AntPath(locations=route).add_to(m) return m
def map_routesf3(lst, map_name): # making list of all coordinates of the NODES avaialble in a cordlst = 0 cordlst = [] for i in lst: cordlst.append(list(G.nodes[i].values())) plugins.AntPath(cordlst).add_to(map_name) return map_name
def read_file_plugin(self): gpx_file = open(self.file, 'r') gpx = gpxpy.parse(gpx_file) points = [] for track in gpx.tracks: for segment in track.segments: for point in segment.points: points.append(tuple([point.latitude, point.longitude])) if self.countTras == 0 or self.countTras % 7 == 0: p = plugins.AntPath(points, color="blue") elif self.countTras == 1 or self.countTras % 6 == 0: p = plugins.AntPath(points, color="darkred") elif self.countTras % 5 == 0: p = plugins.AntPath(points, color="purple") elif self.countTras % 4 == 0: p = plugins.AntPath(points, color="orange") elif self.countTras % 3 == 0: p = plugins.AntPath(points, color="darkblue") elif self.countTras % 2 == 0: p = plugins.AntPath(points, color="green") else: p = plugins.AntPath(points, color="black") return p
def route(): if request.method == "POST": data = pd.read_excel(r'HDBExcel2.xlsx') df = pd.DataFrame(data, columns=['punggol blk_no']) # COLUMN TITLE blkno = data['punggol blk_no'].tolist( ) # GETTING ALL THE BLK NO FROM EXCEL FILE start = request.form.get("start", None) # TAKING THE PARAMETERS end = request.form.get("end", None) # TAKING THE PARAMETERS mode = request.form.get("mode", None) # TAKING THE PARAMETERS path_coords = [] #storing coordinates for each node in path if (mode == "TRANSIT"): #BUSMODE start = "Punggol Temp Int" test = (b.dijsktra(b.graph, start, end)) gBUS.findRouteGraph(start, end) path_coords = b.get_path_coords(b.buslist, c.datahdb, test) elif (mode == "WALKING"): #WALKING MODE HDB-HDB start = "NE17 PTC Punggol" test = (c.dijsktra(c.graph, start, end)) gWALK.findRouteGraph(start, end) path_coords = c.get_path_coords(c.datahdb, c.datamrt, test) else: test = (a.dijsktra(a.graph, start, end)) gLRT.findRouteGraph(start, end) path_coords = a.get_path_coords(c.datahdb, a.datamrt, test) if "Not Possible" not in test[0]: folium_map = folium.Map( location=start_coords, tiles='OpenStreetMap', zoom_start=50, width="100%", height="100%" ) # Reinitialise map to clear all previous markers for i in range(len(path_coords)): folium.CircleMarker(location=path_coords[i], tooltip=test[i], color='blue', fill=False).add_to( folium_map) # Place markers per node # folium.PolyLine(locations=path_coords, smooth_factor=0.1).add_to(folium_map) path_line = plugins.AntPath( locations=path_coords) # Create path line between each nodes path_line.add_to(folium_map) folium_map.save("templates/folium_map.html" ) # save to template for auto reload else: # Reinitialise map to clear all previous markers folium_map = folium.Map(location=start_coords, tiles='OpenStreetMap', zoom_start=50, width="100%", height="100%") folium_map.save('templates/folium_map.html' ) # save to template for auto reload print(start) print(end) print(mode) return render_template("index.html", test=test, blkno=blkno)
def map_routes(lst, map_name): for t in range(len(lst)): cordlst = 0 cordlst = [] a = (lst[t]) for i in a: cordlst.append(list(G.nodes[i].values())) plugins.AntPath(cordlst).add_to(map_name) return map_name
def map_routes(lst, map_name): # making list of all coordinates of the NODES avaialble in a for t in range(len(lst)): cordlst = 0 cordlst = [] a = (lst[t]) for i in a: cordlst.append(list(G.nodes[i].values())) plugins.AntPath(cordlst).add_to(map_name) return map_name
def draw_trajectory(trajectory, MMSI): # trajectory = [[time, lon, lat], [time, lon2, lat2], ... ,[time, lon n, lat n]] # TODO lon、lat的位置要测试一下 # Map构建基本地图图层 m = folium.Map( # lat, lon location=[trajectory[0][2], trajectory[0][1]], zoom_start=10) # 画轨迹 for i in range(1, len(trajectory) - 1): folium.Marker(location=[trajectory[i][2], trajectory[i][1]], popup=get_popup(trajectory[i][0], trajectory[i][1], trajectory[i][2]), icon=folium.Icon(color='red')).add_to(m) # 给每个点画标志 plugins.AntPath( locations=[[x[2], x[1]] for x in trajectory], reverse=False, dash_array=[20, 30], color='#FF0000' # red ).add_to(m) # 轨迹起点 folium.Marker(location=[trajectory[0][2], trajectory[0][1]], popup=get_popup(trajectory[0][0], trajectory[0][1], trajectory[0][2]), icon=folium.Icon(color='blue')).add_to(m) # 轨迹终点 folium.Marker(location=[trajectory[-1][2], trajectory[-1][1]], popup=get_popup(trajectory[-1][0], trajectory[-1][1], trajectory[-1][2]), icon=folium.Icon(color='orange')).add_to(m) m.save(os.path.join(usefule_data_path, str(MMSI) + ".html"))
for home, away in pairings: if (away, home) in seen: h_and_h.add((home, away)) h_and_h.add((away, home)) seen.add((home, away)) for home, away in pairings: # if mapping[home].group != mapping[away].group: # print('**', home, mapping[home].group, away, mapping[away].group) pt1 = mapping[home]['lat'], mapping[home]['lon'] pt2 = mapping[away]['lat'], mapping[away]['lon'] if (home, away) in h_and_h: path = folium.PolyLine([pt1, pt2], color='navy', opacity=0.3) else: path = plugins.AntPath(locations=[pt1, pt2], weight=3, color='navy', delay=3200) path.add_to(pairing_group) map.add_child(pairing_group) show = False # show the first featuregroup only try: pairing_group except NameError: pairing_group = folium.FeatureGroup(name='Teams', show=show) map.add_child(pairing_group) lats = [] lons = [] for i, team in enumerate(teams): print("{:2}. {} {}".format(i + 1, team, team['venue_name']))
def plot(values_meso,last_mile_edges,first_mile_edges): #Create an instance of the map using Folium m = folium.Map(locations=[-112.48849364, 33.3596368342], zoom_start=12, tiles='OpenStreetMap', control_scale=True) #Used to insert Counties into the map data = [json.loads(line) for line in open('/Users/nischalkashyap/Downloads/Fall 2020/Research Assistant GIS/database/djangoapp/geospatial/visualization/templates/visualization/us_geoson.json', 'r')] folium.TopoJson(data[0], 'objects.us_counties_20m', name='topojson').add_to(m) #Based on user selection, project the necessary data onto the map #For First Mile to First Mile if USER_SELECTION == 'FM': #Used to keep track of all the nodes inserted onto the map marked_tracker = [] for i in first_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" #Create markers on the map based on the nodes in the edge entity if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) #Make the edges size based on the fewsion dollar value of that particular edge if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) # For First Mile to Mesoscale elif USER_SELECTION == "FM-MESOSCALE": marked_tracker = [] for i in first_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="blue").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="blue").add_to(m) transfer_data = values_meso[2] all_connections = {} #Logic to identify if any two entries are present which has same source node and destination node #If yes, we tend to aggregate the fewsion_dollar_value for i in transfer_data: if (i[0], i[1]) not in all_connections: all_connections[(i[0], i[1])] = float(i[2]) else: all_connections[(i[0], i[1])] += float(i[2]) #All Connections is a dictionary used to store the aggregated fewsion dollar values of two counties if present in the mesoscale data marked_tracker = [] for i in all_connections: source_county = i[0] destination_county = i[1] #find Coordinates for the source county query = "select latitude,longitude,county_name from county where county_id = '" + str(source_county) + "';" cursor.execute(query) row = cursor.fetchone() #find Coordinates for the destination county query = "select latitude,longitude,county_name from county where county_id = '" + str(destination_county) + "';" cursor.execute(query) row_dest = cursor.fetchone() #Store the fewsion dollar value of the respective edge fewsion_dollar_value = all_connections[i] edge = [[row[0], row[1]], [row_dest[0], row_dest[1]]] popup_source = '<strong>' + row[2] + '</strong>' popup_destination = '<strong>' + row_dest[2] + '</strong>' tooltip = "Click for More Info" # Create markers on the map based on the nodes in the edge entity if source_county not in marked_tracker: folium.Marker([row[0], row[1]], popup=popup_source, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='green')).add_to(m) marked_tracker.append(source_county) folium.Marker([row_dest[0], row_dest[1]], popup=popup_destination, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='green')).add_to(m) marked_tracker.append(destination_county) # plugins.AntPath(edge).add_to(m) -> This code is for displaying flow # Make the edges size based on the fewsion dollar value of that particular edge if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="black").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="black").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) # For Mesoscale to Mesoscale elif USER_SELECTION == "MESOSCALE INFLOWS" or USER_SELECTION=='MESOSCALE OUTFLOWS': transfer_data = values_meso[2] all_connections = {} for i in transfer_data: if (i[0],i[1]) not in all_connections: all_connections[(i[0],i[1])] = float(i[2]) else: all_connections[(i[0], i[1])] += float(i[2]) marked_tracker = [] for i in all_connections: if i[0] == COUNTY_CODE or i[1]==COUNTY_CODE: source_county = i[0] destination_county = i[1] query = "select latitude,longitude,county_name from county where county_id = '"+str(source_county)+"';" cursor.execute(query) row = cursor.fetchone() query = "select latitude,longitude,county_name from county where county_id = '" + str(destination_county) + "';" cursor.execute(query) row_dest = cursor.fetchone() fewsion_dollar_value = all_connections[i] edge = [[row[0],row[1]],[row_dest[0],row_dest[1]]] popup_source = '<a href = "http://127.0.0.1:8000/" target="_blank">Google</a>' #popup_source = '<strong>'+row[2]+'</strong>' popup_destination = '<strong>'+row_dest[2]+'</strong>' tooltip = "Click for More Info" if source_county not in marked_tracker: folium.Marker([row[0],row[1]],popup=popup_source,tooltip = tooltip,icon=folium.Icon (icon='cloud',color='red')).add_to(m) marked_tracker.append(source_county) folium.Marker([row_dest[0], row_dest[1]], popup=popup_destination,tooltip=tooltip,icon=folium.Icon (icon='cloud',color='green')).add_to(m) marked_tracker.append(destination_county) plugins.AntPath(edge).add_to(m) '''if fewsion_dollar_value<1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value>=1 and fewsion_dollar_value<2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m)''' # For Mesocale to Last Mile elif USER_SELECTION == "MESOSCALE-LM": marked_tracker = [] for i in last_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) transfer_data = values_meso[2] all_connections = {} for i in transfer_data: if (i[0], i[1]) not in all_connections: all_connections[(i[0], i[1])] = float(i[2]) else: all_connections[(i[0], i[1])] += float(i[2]) marked_tracker = [] for i in all_connections: source_county = i[0] destination_county = i[1] query = "select latitude,longitude,county_name from county where county_id = '" + str(source_county) + "';" cursor.execute(query) row = cursor.fetchone() query = "select latitude,longitude,county_name from county where county_id = '" + str( destination_county) + "';" cursor.execute(query) row_dest = cursor.fetchone() fewsion_dollar_value = all_connections[i] edge = [[row[0], row[1]], [row_dest[0], row_dest[1]]] popup_source = '<strong>' + row[2] + '</strong>' popup_destination = '<strong>' + row_dest[2] + '</strong>' tooltip = "Click for More Info" if source_county not in marked_tracker: folium.Marker([row[0], row[1]], popup=popup_source, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='red')).add_to(m) marked_tracker.append(source_county) folium.Marker([row_dest[0], row_dest[1]], popup=popup_destination, tooltip=tooltip, icon=folium.Icon (icon='cloud', color='green')).add_to(m) marked_tracker.append(destination_county) plugins.AntPath(edge).add_to(m) '''if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m)''' # For Last Mile to Last Mile elif USER_SELECTION == 'LM': marked_tracker = [] for i in last_mile_edges: val = i.split('*') fewsion_dollar_value = float(val[6]) edge = [[float(val[0]), float(val[1])], [float(val[3]), float(val[4])]] popup_source = '<strong>' + val[2] + '</strong>' popup_destination = '<strong>' + val[5] + '</strong>' tooltip = "Click for More Info" if val[0] + val[1] not in marked_tracker: folium.Marker([float(val[0]), float(val[1])], popup=popup_source, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[0] + val[1]) if val[3] + val[4] not in marked_tracker: folium.Marker([float(val[3]), float(val[4])], popup=popup_destination, tooltip=tooltip, icon=folium.Icon(icon='cloud', color='red')).add_to(m) marked_tracker.append(val[3] + val[4]) if fewsion_dollar_value < 1: folium.PolyLine(edge, weight=1.0, color="green").add_to(m) elif fewsion_dollar_value >= 1 and fewsion_dollar_value < 2: folium.PolyLine(edge, weight=2.0, color="blue").add_to(m) else: folium.PolyLine(edge, weight=3.0, color="black").add_to(m) #Save the Map m.save('visualization/templates/visualization/map.html')
for (i, j) in combo: folium.PolyLine([coordinates[i], coordinates[j]], color='black', weight=1.0, opacity=0.075).add_to(map) points = [] for city in tour: points.append(coordinates[city]) points.append(points[0]) #folium.PolyLine(points, color="blue", weight=5.5, opacity=0.35).add_to(map) #folium.PolyLine([points[0], points[len(points)-1]], color="blue", weight=5.5, opacity=0.35).add_to(map) ant_path = plugins.AntPath(points, tooltip='hello', color='#FF0004', pulse_color='#FFFFFF', dash_array=[11, 15], delay=480) ant_path.add_to(map) count = 0 for each in points[0:len(points) - 1]: popup_text = "{}<br> Latitude: {:,}<br> Longitude: {:,}" popup_text = popup_text.format(tour[count], each[0], each[1]) map.add_child( folium.CircleMarker(location=each, fill='true', radius=7.5, popup=popup_text, fill_color='red',
def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = HTMLmapDialog() if self.dlg.radioButton.isChecked(): self.dlg.pushButton_1.clicked.connect( self.atualizarCoordenadaPartidaOSM) self.dlg.pushButton_2.clicked.connect( self.atualizarCoordenadaChegadaOSM) if self.dlg.radioButton_2.isChecked(): self.dlg.pushButton_1.clicked.connect( self.atualizarCoordenadaPartidaGoogle) self.dlg.pushButton_2.clicked.connect( self.atualizarCoordenadaChegadaGoogle) self.dlg.horizontalSlider.setValue(16) with open( r'C:\OSGeo4W64\apps\qgis\python\plugins\htmlmap\Base\fontawesone.txt', "r") as f: f.readline() for x in f: comboText = self.dlg.comboBox_4.addItem(x) comboText = self.dlg.comboBox_7.addItem(x) comboText = self.dlg.comboBox_10.addItem(x) icon_color = { 'beige', 'black', 'blue', 'cadetblue', 'darkblue', 'darkgreen', 'darkpurple', 'darkred', 'gray', 'green', 'lightblue', 'lightgray', 'lightgreen', 'lightred', 'orange', 'pink', 'purple', 'red', 'white' } add_icon_color = self.dlg.comboBox_3.addItems(icon_color) add_icon_color = self.dlg.comboBox_8.addItems(icon_color) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. latPartida = self.dlg.lineEdit_5.text() lat = float(latPartida) longPartida = self.dlg.lineEdit_6.text() long = float(longPartida) if self.dlg.mGroupBox_8.isChecked(): latChegada = self.dlg.lineEdit_7.text() lat2 = float(latChegada) longChegada = self.dlg.lineEdit_8.text() long2 = float(longChegada) latcentral = (lat + lat2) / 2 longcentral = (long + long2) / 2 lat = latcentral long = longcentral #CRIAR O MAPA/TILE tiles = ('Open Street Map', 'Stamen Terrain', 'Stamen Toner', 'Stamen Watercolor', 'CartoDB Positron', 'CartoDB Dark_Matter') #IMAGEM DE SATÉLITE GOOGLE zoom = self.dlg.horizontalSlider.value() m = folium.Map(location=[lat, long], zoom_start=zoom, tiles=None, prefer_canvas=True) if self.dlg.comboBox.currentText() == 'Google Maps': folium.raster_layers.TileLayer( tiles='http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', attr='google', name='Google Maps', max_zoom=20, subdomains=['mt0', 'mt1', 'mt2', 'mt3'], overlay=False, control=True, ).add_to(m) if self.dlg.comboBox.currentText() == 'Google Earth': folium.raster_layers.TileLayer( tiles='http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', attr='google', name='Google Earth', max_zoom=20, subdomains=['mt0', 'mt1', 'mt2', 'mt3'], overlay=False, control=True).add_to(m) if self.dlg.comboBox.currentText( ) == 'Open Street Map' or 'Stamen Terrain' or 'Stamen Toner' or 'Stamen Watercolor' or 'CartoDB Positron' or 'CartoDB Dark_Matter': folium.raster_layers.TileLayer( tiles=self.dlg.comboBox.currentText(), attr='google', name=self.dlg.comboBox.currentText(), max_zoom=20, control_scale=True).add_to(m) #MINIMAP if self.dlg.checkBox.isChecked(): minimap = plugins.MiniMap(position='bottomright', toggle_display=True, width=100, height=100, zoom_level_offset=-4, center_fixed=False, zoom_animation=True, minimized=False) m.add_child(minimap) #DESENHAR NA TELA if self.dlg.checkBox_2.isChecked(): draw = plugins.Draw(position='bottomright', export=True) draw.add_to(m) #MEDIÇÃO EM TELA DE DISTANCIA E ÁREA if self.dlg.checkBox_3.isChecked(): measure_control = plugins.MeasureControl( position='topright', active_color='red', completed_color='red', primary_lenght_unit='meters') m.add_child(measure_control) # ADICIONAR ALGUMA IMAGEM NA TELA if self.dlg.checkBox_4.isChecked(): url = self.dlg.mQgsFileWidget_5.filePath() FloatImage(url, bottom=92, left=1).add_to(m) #TELA CHEIA if self.dlg.checkBox_5.isChecked(): plugins.Fullscreen(position='topleft').add_to(m) #LOCALIZAÇÃO DA PESSOA if self.dlg.checkBox_6.isChecked(): plugins.LocateControl(position='topleft').add_to(m) if self.dlg.checkBox_8.isChecked(): # If you want get the user device positon after load the map, set auto_start=True plugins.LocateControl(auto_start=True).add_to(m) #LATITUDE E LONGITUDE PARA CLIQUES NO MAPA if self.dlg.checkBox_7.isChecked(): m.add_child(folium.LatLngPopup()) subgrupos = folium.FeatureGroup(name='Estilos de Mapas', control=False, show=False) m.add_child(subgrupos) if self.dlg.mGroupBox.isChecked(): opcao1 = plugins.FeatureGroupSubGroup( subgrupos, self.dlg.lineEdit_11.text(), show=True) m.add_child(opcao1) if self.dlg.mGroupBox_2.isChecked(): opcao2 = plugins.FeatureGroupSubGroup( subgrupos, self.dlg.lineEdit_12.text(), show=True) m.add_child(opcao2) if self.dlg.mGroupBox_3.isChecked(): opcao3 = plugins.FeatureGroupSubGroup( subgrupos, self.dlg.lineEdit_10.text(), show=True) m.add_child(opcao3) if self.dlg.mGroupBox_8.isChecked(): opcao4 = plugins.FeatureGroupSubGroup(subgrupos, 'Rota', show=True) m.add_child(opcao4) #PONTO if self.dlg.mGroupBox.isChecked(): PontosEntrada = self.dlg.mQgsFileWidget.filePath() PontosJSON = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Pontos_json.geojson' gj = folium.GeoJson(PontosJSON) popupPontos = self.dlg.lineEdit.text() processing.run( "native:reprojectlayer", { 'INPUT': PontosEntrada, 'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'), 'OPERATION': '+proj=pipeline +step +inv +proj=utm +zone=22 +south +ellps=GRS80 +step +proj=unitconvert +xy_in=rad +xy_out=deg', 'OUTPUT': PontosJSON }) for feature in gj.data['features']: if feature['geometry']['type'] == 'Point': if self.dlg.comboBox_2.currentText() == 'Pin': icon = self.dlg.comboBox_4.currentText() color = self.dlg.mColorButton_11.color().name() icon_color = self.dlg.mColorButton_5.color().name() folium.Marker(location=list( reversed(feature['geometry']['coordinates'])), popup=popupPontos, icon=folium.Icon( icon=icon, color=color, icon_color=icon_color, prefix='fa')).add_to(opcao1) if self.dlg.comboBox_2.currentText( ) == 'Beautify Icon': icon = self.dlg.comboBox_4.currentText() icon_color = self.dlg.mColorButton_5.color().name() color = 'transparent' tamanho = self.dlg.doubleSpinBox_4.value() icon_size = (tamanho, tamanho) icon_plane = plugins.BeautifyIcon( icon=icon, icon_size=icon_size, border_color='transparent', background_color=color, innerIconStyle= 'font-size:20px;padding-top:1px;', text_color=icon_color) folium.Marker(location=list( reversed(feature['geometry']['coordinates'])), popup=popupPontos, icon=icon_plane).add_to(opcao1) #LINHA if self.dlg.mGroupBox_2.isChecked(): LinhaEntrada = self.dlg.mQgsFileWidget_2.filePath() LinhaJSON = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Linha_json.geojson' espessura = self.dlg.doubleSpinBox_5.value() color = self.dlg.mColorButton.color().name() borda = self.dlg.mColorButton_13.color().name() popupLinhas = self.dlg.lineEdit_9.text() processing.run( "native:reprojectlayer", { 'INPUT': LinhaEntrada, 'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'), 'OPERATION': '+proj=pipeline +step +inv +proj=utm +zone=22 +south +ellps=GRS80 +step +proj=unitconvert +xy_in=rad +xy_out=deg', 'OUTPUT': LinhaJSON }) styleLinha = { "fillOpacity": 1, 'fillColor': borda, 'color': color, "weight": espessura, "opacity": 1.0 } folium.GeoJson(LinhaJSON, style_function=lambda x: styleLinha, popup=popupLinhas).add_to(opcao2) #POLÍGONO if self.dlg.mGroupBox_3.isChecked(): PoligonoEntrada = self.dlg.mQgsFileWidget_3.filePath() popupPoligono = self.dlg.lineEdit_2.text() color = self.dlg.mColorButton_3.color().name() borda = self.dlg.mColorButton_2.color().name() transparencia = self.dlg.doubleSpinBox.value() PoligonoJSON = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Poligono_json.geojson' processing.run( "native:reprojectlayer", { 'INPUT': PoligonoEntrada, 'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'), 'OPERATION': '+proj=pipeline +step +inv +proj=utm +zone=22 +south +ellps=GRS80 +step +proj=unitconvert +xy_in=rad +xy_out=deg', 'OUTPUT': PoligonoJSON }) stylePoligono = { 'fillColor': color, "fillOpacity": transparencia, 'color': borda, "weight": self.dlg.doubleSpinBox_2.value() } folium.GeoJson( PoligonoJSON, style_function=lambda x: stylePoligono).add_to(opcao3) #ADICIONAR IMAGEM - CERTO # url = 'http://leafletjs.com/examples/custom-icons/{}'.format # icon_image = url('leaf-red.png') # icon3d = 'https://www.pngfind.com/pngs/m/218-2181815_download-setas-em-3d-png-images-background-setas.png' # icon = CustomIcon(icon3d,icon_size=(19,47)) # marker = folium.Marker(location=[-25.4528, -49.2323],icon=icon,popup='Árvore') # m.add_child(marker) # icon_plane = plugins.BeautifyIcon(icon='tree', border_color='transparent', backgroundColor = 'transparent', iconSize= (22,22), border_width = 0.1, text_color='#83ca57',inner_icon_style='font-size:20px;padding-top:1px;') # icon_number = plugins.BeautifyIcon(iconSize = (15, 15), border_width = 0, text_color='#000000', backgroundColor = 'transparent', number='A',inner_icon_style='font-size:15px') # coord_arvores = [-25.4523, -49.2326] # folium.Marker(location=coord_arvores,popup='Árvore', icon=icon_plane).add_to(m) # folium.Marker(location=[-25.4527, -49.2331],popup='Bloco', icon=icon_number).add_to(m) #folium.LayerControl(collapsed=True).add_to(m) #icon3d = r'C:\Users\fabri\Desktop\Imagem1.svg' #icon = CustomIcon(icon3d,icon_size=(19,47)) #marker = folium.Marker(location=[-25.4528, -49.2323],icon=icon,popup='Árvore') #m.add_child(marker) #ORIGEM latPartida = self.dlg.lineEdit_5.text() latPartida = float(latPartida) longPartida = self.dlg.lineEdit_6.text() longPartida = float(longPartida) startPoint = '%s, %s [EPSG:4326]' % ( longPartida, latPartida) #'-46.505448,-18.578563 [EPSG:4326]' if self.dlg.comboBox_9.currentText() == 'Pin': icon = self.dlg.comboBox_7.currentText() color = self.dlg.comboBox_3.currentText() icon_color = self.dlg.mColorButton_7.color().name() folium.Marker(location=[latPartida, longPartida], popup='Início', icon=folium.Icon(icon=icon, color=color, icon_color=icon_color, prefix='fa')).add_to(m) if self.dlg.comboBox_9.currentText() == 'Beautify Icon': icon = self.dlg.comboBox_7.currentText() #color = self.dlg.comboBox_7.currentText() color = 'transparent' icon_color = self.dlg.mColorButton_7.color().name() icon_size = (10, 10) icon_plane = plugins.BeautifyIcon( icon=icon, prefix='fa', icon_size=icon_size, border_color='transparent', background_color=color, innerIconStyle='font-size:20px;padding-top:1px;', text_color=icon_color) folium.Marker(location=[latPartida, longPartida], popup='Início', icon=icon_plane).add_to(m) #ROTA if self.dlg.mGroupBox_8.isChecked(): latPartida = self.dlg.lineEdit_5.text() latPartida = float(latPartida) longPartida = self.dlg.lineEdit_6.text() longPartida = float(longPartida) latChegada = self.dlg.lineEdit_7.text() latChegada = float(latChegada) longChegada = self.dlg.lineEdit_8.text() longChegada = float(longChegada) lat, long = [round(latPartida, 3), round(latChegada, 3) ], [round(longPartida, 3), round(longChegada, 3)] minlong, maxlong, minlat, maxlat = [ min(long) + 0.3, max(long) - 0.3, min(lat) + 0.3, max(lat) - 0.3 ] extensao = '%s, %s, %s, %s [EPSG:4326]' % (minlong, maxlong, minlat, maxlat) redeOSM = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Curitiba_vias01.shp' #malhaRota = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/cortado.gpkg' #processing.run("native:extractbyextent", {'INPUT':redeOSM,'EXTENT':extensao,'CLIP':False,'OUTPUT':malhaRota}) startPoint = '%s, %s [EPSG:4326]' % ( longPartida, latPartida ) #'-46.505448,-18.578563 [EPSG:4326]' finalPoint = '%s, %s [EPSG:4326]' % ( longChegada, latChegada ) #'-46.507785,-18.577713 [EPSG:4326]' Ponto2 = '%s, %s' % (longChegada, latChegada) if self.dlg.comboBox_12.currentText() == 'Pin': icon = self.dlg.comboBox_10.currentText() color = self.dlg.comboBox_8.currentText() icon_color = self.dlg.mColorButton_8.color().name() folium.Marker(location=[latChegada, longChegada], popup='Chegada', icon=folium.Icon(icon=icon, color=color, icon_color=icon_color, prefix='fa')).add_to(opcao4) if self.dlg.comboBox_12.currentText() == 'Beautify Icon': icon = self.dlg.comboBox_10.currentText() icon_color = self.dlg.mColorButton_8.color().name() color = 'transparent' icon_size = (10, 10) icon_plane = plugins.BeautifyIcon( icon=icon, icon_size=icon_size, border_color='transparent', background_color=color, innerIconStyle='font-size:20px;padding-top:1px;', text_color=icon_color) folium.Marker(location=[latChegada, longChegada], popup='Chegada', icon=icon_plane).add_to(opcao4) rota = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/rota.geojson' processing.run( "native:shortestpathpointtopoint", { 'INPUT': redeOSM, 'STRATEGY': 0, 'DIRECTION_FIELD': None, 'VALUE_FORWARD': '', 'VALUE_BACKWARD': '', 'VALUE_BOTH': '', 'DEFAULT_DIRECTION': 2, 'SPEED_FIELD': None, 'DEFAULT_SPEED': 50, 'TOLERANCE': 0, 'START_POINT': startPoint, 'END_POINT': finalPoint, 'OUTPUT': rota }) with open(rota) as f: data = json.load(f) for feature in data['features']: coordenadasRota = (feature['geometry']['coordinates']) coord_list = [] for coord_pair in coordenadasRota: json_coord_pair = {} json_coord_pair = [(coord_pair[1]), (coord_pair[0])] coord_list.append(json_coord_pair) cor_rota = self.dlg.mColorButton_4.color().name() cor_simbolo = self.dlg.mColorButton_6.color().name() if self.dlg.mGroupBox_10.isChecked(): formato_simbolo = self.dlg.comboBox_5.currentText() if self.dlg.comboBox_5.currentText() == 'Arredondado': formato_simbolo = 'round' if self.dlg.comboBox_5.currentText() == 'Quadrado': formato_simbolo = 'butt' if self.dlg.comboBox_5.currentText() == 'Retangular': formato_simbolo = 'square' juncao = self.dlg.comboBox_6.currentText() if self.dlg.comboBox_6.currentText() == 'Arredondado': juncao = 'round' if self.dlg.comboBox_6.currentText() == 'Reto': juncao = 'mitter' if self.dlg.comboBox_6.currentText() == 'Cortado': juncao = 'bevel' plugins.AntPath( [coord_list], popup='Rota', color=cor_rota, weight=self.dlg.doubleSpinBox_8.value(), opacity=1, delay=self.dlg.spinBox_3.value(), line_cap=formato_simbolo, line_join=juncao, dash_array=[10, 20], pulse_color=cor_simbolo, reverse=True, hardwareAccelerated=True).add_to(opcao4) else: plugins.AntPath( [coord_list], popup='Rota', color=cor_rota, weight=self.dlg.doubleSpinBox_8.value(), opacity=1, pulse_color=cor_rota, delay=0).add_to(opcao4) #SALVAR MAPA folium.LayerControl(collapsed=True).add_to(m) salvarHTML = self.dlg.mQgsFileWidget_4.filePath() + ".html" m_save = m.save(salvarHTML) message = ("Finalizado: O arquivo foi processado e salvo.") self.iface.messageBar().pushMessage(message, level=0, duration=10)
popup='Tower', icon=folium.Icon(color='black', icon='info-sign')).add_to(map_robi) folium.Marker(location=[23.737054, 90.369061], popup='Start from Here', icon=folium.Icon(color='red', icon='info-sign')).add_to(map_robi) for (index, row) in data.iterrows(): folium.Marker(location=[row.loc['lat'], row.loc['long']], popup='shop:' + str(row.loc['sr']), tooltip='click').add_to(map_robi) # route_lats_longs = [[23.6515, 90.6573], [23.7595, 90.7595]] folium.PolyLine(lst).add_to(map_robi) plugins.AntPath(lst).add_to(map_robi) folium_static(map_robi) file2.close() st.subheader("To do reset click on the reset button") if st.button("Reset"): file3 = open("tusher.txt", "w") st.write("Now you can add lines again") file3.write("0") file3.close() #### df = pandas.read_csv('location.csv') df2 = pandas.read_csv('location2.csv') L2 = [] folium.Map(location=[23.741256, 90.370660], zoom_start=80)
def seeshortestway(x1, x2): #loc1 = ox.geocode(x1) #loc2 = ox.geocode(x2) place1 = gmaps.geocode(x1) lat1 = place1[0]['geometry']['location']['lat'] lng1 = place1[0]['geometry']['location']['lng'] place2 = gmaps.geocode(x2) lat2 = place2[0]['geometry']['location']['lat'] lng2 = place2[0]['geometry']['location']['lng'] loc1 = (lat1, lng1) loc2 = (lat2, lng2) #KD트리를 이용하면 최단거리를 쉽고 효율적으로 찾아준다. tree = KDTree(nodes[['y', 'x']], metric='euclidean') loc1_idx = tree.query([loc1], k=1, return_distance=False)[0] loc2_idx = tree.query([loc2], k=1, return_distance=False)[0] closest_node_to_loc1 = nodes.iloc[loc1_idx].index.values[0] closest_node_to_loc2 = nodes.iloc[loc2_idx].index.values[0] route = nx.shortest_path(G, closest_node_to_loc1, closest_node_to_loc2, weight='length') onlygodoroute = nx.shortest_path(G, closest_node_to_loc1, closest_node_to_loc2, weight='grade_abs') impedanceroute = nx.shortest_path(G, closest_node_to_loc1, closest_node_to_loc2, weight='impedance') #distance=nx.shortest_path_length(G, closest_node_to_loc1,closest_node_to_loc2) graderoute = [] impedance = [] for i in range(len(onlygodoroute)): lng = G.node[onlygodoroute[i]]['x'] lat = G.node[onlygodoroute[i]]['y'] b = [lat, lng] graderoute.append(b) for i in range(len(impedanceroute)): lng = G.node[impedanceroute[i]]['x'] lat = G.node[impedanceroute[i]]['y'] b = [lat, lng] impedance.append(b) m = ox.plot_route_folium(G, route, route_color='navy', tiles='stamen toner') antpath = plugins.AntPath(locations=graderoute, color='purple') antpath.add_to(m) antpath = plugins.AntPath(locations=impedance, color='red') antpath.add_to(m) #folium.PolyLine(graderoute, color="purple", weight=4).add_to(m) #folium.PolyLine(impedance, color="red", weight=4).add_to(m) kw = {'prefix': 'fa', 'color': 'green', 'icon': 'arrow-up'} ka = {'prefix': 'fa', 'color': 'blue', 'icon': 'arrow-up'} icon1 = folium.Icon(angle=45, **kw) folium.Marker(location=loc1, icon=icon1, popup=x1, tooltip='출발').add_to(m) icon2 = folium.Icon(angle=180, **ka) folium.Marker(location=loc2, icon=icon2, popup=x2, tooltip='도착').add_to(m) #lium.Marker(location=loc1, # icon=folium.Icon(color='red'), popup=x1, tooltip='출발').add_to(m) #folium.Marker(location=loc2, #icon=folium.Icon(color='blue'),popup=x2, tooltip='도착').add_to(m) dobo = 4 add = [] for i in range(len(route) - 1): lng1 = G.node[route[i]]['x'] lat1 = G.node[route[i]]['y'] lng2 = G.node[route[i + 1]]['x'] lat2 = G.node[route[i + 1]]['y'] result = GeoUtil.get_harversion_distance(lng1, lat1, lng2, lat2) add.append(result) noroundkm = sum(add) km = round(noroundkm, 1) noroundminute = (km / dobo) * 60 minute = round(noroundminute, 1) print('거리는', km, 'KM 이며, ', '시간은', minute, '분 걸립니다.') return m
# Analysis ************************************************************************************************************* vals = model.getAttr('x', des_vars) selected = guro.tuplelist((i, j) for (i, j) in vals.keys() if vals[i, j] > 0.5) tour = get_cycle(selected) assert len(tour) == len(locations) points = [] for city in tour: points.append(coordinates[city]) points.append(points[0]) ant_path = plugins.AntPath(points, tooltip='hello', color='white', pulse_color='crimson', dash_array=[11, 15], delay=800, weight=4) ant_path.add_to(folium_map) # Every Possible Path combo = [(i, j) for (i, j) in product(locations, locations) if i != j] for (i, j) in combo: folium.PolyLine([coordinates[i], coordinates[j]], color='black', weight=3.0, opacity=0.175).add_to(folium_map) # --------------------------------------------auto_open----------------------------------------------------------------- def auto_open(path, f_map): html_page = f'{path}' f_map.save(html_page)
great = (np.array(great)) bad = (np.array(bad)) print(great, '\nclosed:\n', bad) solve_map = folium.Map([51.1380, 16.7294], zoom_start=8) for i in range(great.shape[0]): folium.Marker((great[i, :]), popup=globals()['facility%s' % lpg[i]], icon=folium.Icon(color='green')).add_to(solve_map) for i in range(bad.shape[0]): folium.Marker((bad[i, :]), popup='Magazyn %i jest zamkniety' % lpb[i], icon=folium.Icon(color='red')).add_to(solve_map) for i in range(costumers.shape[0]): folium.Marker((costumers[i, :]), popup=globals()['costumer%s' % i], icon=folium.Icon(color='blue')).add_to(solve_map) for i in range(fac_cos.shape[0]): tripid = str(fac_cos[i, 0]) + str(fac_cos[i, 1]) print(tripid) plugins.AntPath(globals()['trip%s' % tripid], color='blue').add_to(solve_map) solve_map.save('Solve.html') print("--- %s seconds ---" % (time.time() - start_time)) print("fajnie było")