-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhosp_qgis.py
193 lines (159 loc) · 7.12 KB
/
hosp_qgis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import qgis
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
import sys
import os
from qgis.analysis import QgsNativeAlgorithms
from qgis.PyQt.QtWidgets import QAction, QMainWindow
# Instantiate the QGIS Application
GUIEnabled = False
app = QgsApplication([], GUIEnabled)
# Update prefix path
app.setPrefixPath("C:/OSGeo4W64/apps/qgis", True) # Folder where qgis is located
app.initQgis()
# User inputs
spc = input("Select Hospital Speciality\n1. Cardiology\n2. Gynaecology\n3. Neurology\n4. Orthopedic Surgeon\n5. Physiology\n6. Surgeon\n7. Allergist\n8. Children's Hospital\n")
typ = input("Select Hospital type\n1. Private\n2. Government\n3. Trust\n4. All\n")
flag = 0
spcl = {'1': 'cardio', '2': 'Gyneco', '3':'Neuro', '4':'Orthopedic', '5':'Physio', '6':'Surgeon', '7':'allergist', '8':'Children_Hospital'}
typ1 = {'1':'private', '2': 'government', '3':'trust', '4':'all'}
# Adding layers
uri = "Hospital_final.csv"
vlayer = QgsVectorLayer(uri, "Hosp_final", "ogr")
path = "http://server.arcgisonline.com/arcgis/rest/services/ESRI_Imagery_World_2D/MapServer?f=json&pretty=true"
rlayer = QgsRasterLayer(path, "raster")
if vlayer.isValid():
print("Valid")
else:
print("Invalid")
cost = dict()
sys.path.append('C:/OSGeo4W64/apps/qgis/python/plugins') # Folder where Processing is located
from processing.core.Processing import Processing
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
print("Processing initiated\n")
from processing.tools import *
import processing
# Create map canvas
class MyWnd(QMainWindow):
def __init__(self, layer, src, dst):
QMainWindow.__init__(self)
self.canvas = QgsMapCanvas()
self.canvas.setCanvasColor(Qt.white)
self.canvas.setExtent(layer.extent())
self.canvas.setLayers([layer,src,dst,rlayer])
self.setCentralWidget(self.canvas)
self.actionZoomIn = QAction("Zoom in", self)
self.actionZoomOut = QAction("Zoom out", self)
self.actionPan = QAction("Pan", self)
self.actionZoomIn.setCheckable(True)
self.actionZoomOut.setCheckable(True)
self.actionPan.setCheckable(True)
self.actionZoomIn.triggered.connect(self.zoomIn)
self.actionZoomOut.triggered.connect(self.zoomOut)
self.actionPan.triggered.connect(self.pan)
self.toolbar = self.addToolBar("Canvas actions")
self.toolbar.addAction(self.actionZoomIn)
self.toolbar.addAction(self.actionZoomOut)
self.toolbar.addAction(self.actionPan)
# create the map tools
self.toolPan = QgsMapToolPan(self.canvas)
self.toolPan.setAction(self.actionPan)
self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
self.toolZoomIn.setAction(self.actionZoomIn)
self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
self.toolZoomOut.setAction(self.actionZoomOut)
self.pan()
def zoomIn(self):
self.canvas.setMapTool(self.toolZoomIn)
def zoomOut(self):
self.canvas.setMapTool(self.toolZoomOut)
def pan(self):
self.canvas.setMapTool(self.toolPan)
# Finding features and processing algorithm
for feature in vlayer.getFeatures():
if typ1[typ] == 'all':
print(feature["Hospital_name"])
lat = feature["Location-Latitude"]
long = feature["Location-Longitude"]
#print(lat, long)
dest = long+","+lat+" [EPSG:4326]"
print(dest)
result = general.run("native:shortestpathpointtopoint", {'INPUT':'hosp_road.shp','STRATEGY':0,'DIRECTION_FIELD':None,'VALUE_FORWARD':'','VALUE_BACKWARD':'','VALUE_BOTH':'','DEFAULT_DIRECTION':2,'SPEED_FIELD':None,'DEFAULT_SPEED':50,'TOLERANCE':0,'START_POINT':'73.02217460971042,19.04214447607201 [EPSG:4326]','END_POINT':dest,'OUTPUT':'memory:'})
print("Travel Cost:",result['TRAVEL_COST'],"\n")
cost[dest,feature["Hospital_name"]] = result['TRAVEL_COST']
flag += 1
elif typ1[typ] in feature["Hospital_Type"] and spcl[spc] in feature["Hospital_speciality"]:
print(feature["Hospital_name"])
lat = feature["Location-Latitude"]
long = feature["Location-Longitude"]
#print(lat, long)
dest = long+","+lat+" [EPSG:4326]"
print(dest)
result = general.run("native:shortestpathpointtopoint", {'INPUT':'hosp_road.shp','STRATEGY':0,'DIRECTION_FIELD':None,'VALUE_FORWARD':'','VALUE_BACKWARD':'','VALUE_BOTH':'','DEFAULT_DIRECTION':2,'SPEED_FIELD':None,'DEFAULT_SPEED':50,'TOLERANCE':0,'START_POINT':'73.02217460971042,19.04214447607201 [EPSG:4326]','END_POINT':dest,'OUTPUT':'memory:'})
print("Travel Cost:",result['TRAVEL_COST'],"\n")
cost[dest,feature["Hospital_name"]] = result['TRAVEL_COST']
flag += 1
if flag == 0:
print("Sorry! No such hospital found.")
quit()
min_cost = min(cost.keys(), key=(lambda k: cost[k]))
#print(min_cost)
dest = min_cost[0]
print("Nearest Hospital:",min_cost[1])
result = general.run("native:shortestpathpointtopoint", {'INPUT':'C:/Users/acer/Downloads/hosp_road.shp','STRATEGY':0,'DIRECTION_FIELD':None,'VALUE_FORWARD':'','VALUE_BACKWARD':'','VALUE_BOTH':'','DEFAULT_DIRECTION':2,'SPEED_FIELD':None,'DEFAULT_SPEED':50,'TOLERANCE':0,'START_POINT':'73.02217460971042,19.04214447607201 [EPSG:4326]','END_POINT':dest,'OUTPUT':'memory:'})
travel_cost = result['TRAVEL_COST']
travel_cost = round((travel_cost/1000), 2)
print("Distance: ", travel_cost, " km")
output_layer = r"C:/Users/acer/Desktop/KML"
QgsVectorFileWriter.writeAsVectorFormat(result['OUTPUT'], output_layer, "utf-8", result['OUTPUT'].crs(), "KML")
temp = dest.split(',')
temp[0] = float(temp[0])
temp1 = temp[1].split(' ')
temp1[0] = float(temp1[0])
source = QgsVectorLayer('Point', 'points' , "memory")
pr = source.dataProvider()
# add the source point
pt = QgsFeature()
point1 = QgsPointXY(73.02217460971042,19.04214447607201)
pt.setGeometry(QgsGeometry.fromPointXY(point1))
pr.addFeatures([pt])
# update extent of the layer
source.updateExtents()
source.renderer().symbol().setSize(3.0)
source.renderer().symbol().setColor(QColor("yellow"))
source.triggerRepaint()
destination = QgsVectorLayer('Point', 'points' , "memory")
pr = destination.dataProvider()
# add the destination point
pt = QgsFeature()
point2 = QgsPointXY(temp[0],temp1[0])
pt.setGeometry(QgsGeometry.fromPointXY(point2))
pr.addFeatures([pt])
# update extent
destination.updateExtents()
destination.renderer().symbol().setSize(3.0)
destination.renderer().symbol().setColor(QColor("red"))
destination.triggerRepaint()
#print(result['OUTPUT'])
#QgsProject.instance().addMapLayers([result['OUTPUT']])
# Processing the output
result['OUTPUT'].renderer().symbol().setWidth(1.0)
result['OUTPUT'].renderer().symbol().setColor(QColor("blue"))
result['OUTPUT'].triggerRepaint()
w = MyWnd(result['OUTPUT'],source,destination)
w.show()
'''canvas = QgsMapCanvas()
canvas.setCanvasColor(Qt.white)
canvas.enableAntiAliasing(True)
canvas.setExtent(result['OUTPUT'].extent())
canvas.setLayers([vlayer,result['OUTPUT'],rlayer])
canvas.freeze(True)
canvas.show()'''
exitcode = app.exec_()
app.exitQgis()
sys.exit(exitcode)