In addition to geocoding addresses, the geocoding service can also be used to find points of interest (POI) of several different kinds. In Part 3, we will explain briefly about category
parameter of geocode()
function and its applications.
Getting started
First, Let's look at some Quickstart examples, which show how the category
attributes change based on the search string.
Search for administrative place names
The geocode()
method supports single field and multi-field searches for administrative place names. This includes searches for neighborhoods, cities, counties, states, provinces, or countries. If a search for a city name results in multiple matches with the same name, the World Geocoding Service will sort the candidates in order of their relative importance to each other (as indicated by the value of the Rank output field), with priority generally based on population and capital status.
For example, there are many cities in the world named Liverpool
, so a search for "Liverpool" results in several equivalent matches; Liverpool, UK
will always be the top candidate since it has the greatest population.
from arcgis.geocoding import geocode
from arcgis.gis import GIS
from arcgis.map import Map
from arcgis.map.popups import PopupInfo
gis = GIS(profile="your_enterprise_profile")
address = "Liverpool"
map1 = Map("United Kingdom")
map1
map1.zoom = 6
liverpool = geocode(address)[0]
liverpool['location'].update({"spatialReference" : {"wkid" : 4326}})
map1.content.draw(liverpool['location'])
However, rank alone is not always enough to distinguish between administrative places. Also, you may not necessarily want to find the highest-ranked feature for a particular search. It may be necessary to remove ambiguity by refining searches with additional information. For example, a search for Liverpool
returns Liverpool, UK
as the top candidate based on rank. If you instead want to find the town of Liverpool, New York, it is necessary to add the state information to the search.
address = {
"Address" : "Liverpool",
"Region" : "NY"
}
map2 = Map("Onondaga County, New York, United States")
map2
liverpool = geocode(address)[0]
liverpool['location'].update({"spatialReference" : {"wkid" : 4326}})
map2.content.draw(liverpool['location'])
Example of finding landmarks
The geocode()
method can be used to find famous landmarks. The example below geocodes and maps Mt. Everest in Asia, Eiffel Tower in Europe, and the Statue of Liberty in North America:
landmarks = ["Mt. Everest", "Eiffel Tower", "Statue of Liberty"]
map3 = Map()
map3
for lm in landmarks:
lm_res = geocode(lm)[0]
lm_res['location'].update({"spatialReference" : {"wkid" : 4326}})
map3.content.draw(lm_res['location'])
Search for postal codes
The geocode()
method supports searches for postal codes and postal code extensions. When searching for postal codes, it is important to note that the same code can be valid in more than one country. For the best results, it may be necessary to include additional information with the postal code, such as city or country.
address = {
"Postal" : 110001,
"CountryCode" : "India"
}
map4 = Map("New Delhi, India")
map4
pincode = geocode(address)[0]
pincode['location'].update({"spatialReference" : {"wkid" : 4326}})
map4.content.draw(pincode['location'])
The matched address contains several attributes that provide values for the various output fields supported by the geocoder, as listed below:
pincode['attributes']
{'Loc_name': 'World', 'Status': 'M', 'Score': 100, 'Match_addr': '110001, New Delhi, Delhi', 'LongLabel': '110001, New Delhi, Delhi, IND', 'ShortLabel': '110001', 'Addr_type': 'Postal', 'Type': '', 'PlaceName': '110001', 'Place_addr': 'Connaught Place, New Delhi, Delhi, 110001', 'Phone': '', 'URL': '', 'Rank': 5, 'AddBldg': '', 'AddNum': '', 'AddNumFrom': '', 'AddNumTo': '', 'AddRange': '', 'Side': '', 'StPreDir': '', 'StPreType': '', 'StName': '', 'StType': '', 'StDir': '', 'BldgType': '', 'BldgName': '', 'LevelType': '', 'LevelName': '', 'UnitType': '', 'UnitName': '', 'SubAddr': '', 'StAddr': '', 'Block': '', 'Sector': 'Chelmsford Lane', 'Nbrhd': '', 'District': 'Connaught Place', 'City': 'New Delhi', 'MetroArea': 'New Delhi', 'Subregion': 'New Delhi', 'Region': 'Delhi', 'RegionAbbr': 'DL', 'Territory': '', 'Zone': '', 'Postal': '110001', 'PostalExt': '', 'Country': 'IND', 'CntryName': 'India', 'LangCode': 'ENG', 'Distance': 0, 'X': 77.218791, 'Y': 28.6324252, 'DisplayX': 77.218791, 'DisplayY': 28.6324252, 'Xmin': 77.195791, 'Xmax': 77.241791, 'Ymin': 28.6094252, 'Ymax': 28.6554252, 'ExInfo': ''}
Note that if users want to get exact administrative boundaries, they can do so by using geoenrichment as shown here.
Example of finding multiple categories
In the example below, we search for Indian and Thai Food in Los Angeles, and plot their locations using different symbols based on the Type
attribute:
categories = "Indian Food, Thai Food"
map5 = Map("Downtown, Los Angeles, CA")
map5
dtla = geocode("Downtown, Los Angeles, CA")[0]
# find and plot up to 100 Indian and Thai restaurants in DTLA
restaurants = geocode(None, dtla['extent'], category=categories, max_locations=100)
from arcgis.map.symbols import SimpleMarkerSymbolEsriSMS, SimpleMarkerSymbolStyle, SimpleLineSymbolEsriSLS
thai_symbol = SimpleMarkerSymbolEsriSMS(
style=SimpleMarkerSymbolStyle.esri_sms_square,
color=[76,115,0,255],
size=8,
angle=0,
xoffset=0,
yoffset=0,
outline=SimpleLineSymbolEsriSLS(
color=[152,230,0,255],
width=1
)
)
indian_symbol = SimpleMarkerSymbolEsriSMS(
style=SimpleMarkerSymbolStyle.esri_sms_circle,
color=[115,0,76,255],
size=8,
angle=0,
xoffset=0,
yoffset=0,
outline=SimpleLineSymbolEsriSLS(
color=[152,230,0,255],
width=1
)
)
for restaurant in restaurants:
popup = PopupInfo(**{
"title" : restaurant['address'],
"description" : "Phone: " + restaurant['attributes']['Phone']
})
restaurant['location'].update({"spatialReference" : {"wkid" : 4326}})
if restaurant['attributes']['Type'] == 'Thai Food':
map5.content.draw(restaurant['location'], popup, thai_symbol) # use a green square symbol for Thai food
else:
map5.content.draw(restaurant['location'], popup, indian_symbol)
Example of finding hospitals within 10 mile buffer around Esri HQ and distance to each
Next, let's walk through the example of finding hospitals within a 10-mile buffer around Esri Headquarter (HQ) and computing distances from Esri to each hospital. The steps of implementation in this section would include:
- Creating a Point object for Esri HQ, use the
geometry
module to build abuffer
, and then applying it assearch_extent
parameter. - Getting
geocode()
results as aFeatureSet
, iterating through each feature within, and usingdistance()
to compute the distance from the originalPoint
to the feature. - Presenting results as a
DataFrame
showing different columns along with distance, and plotting the distance as a bar chart. - Plotting the
FeatureSet
on the map with appropriate symbols (using the an url location) or programmatically create these symbols).
Step 1. Create a Point object for Esri HQ, and build a buffer
esrihq_fset = geocode("Esri", as_featureset=True)
esrihq_fset
<FeatureSet> 20 features
esri_geom = esrihq_fset.features[0]
esri_geom.geometry.JSON
'{"x": -117.195695233, "y": 34.0560864, "spatialReference": {"wkid": 4326, "latestWkid": 4326}}'
from arcgis.features import Feature, FeatureSet
from arcgis.geometry import buffer
esri_buffer = buffer([esri_geom.geometry],
in_sr = 102100, buffer_sr=102100,
distances=0.1, unit=9001)[0]
esri_buffer_f = Feature(geometry=esri_buffer)
esri_buffer_fset = FeatureSet([esri_buffer_f])
esri_buffer_fset
<FeatureSet> 1 features
# need to change the `type` from `MultiPolygon` to `Polygon`
esri_buffer_f_geom_dict = {"type": "Polygon",
"coordinates": esri_buffer_f.geometry.coordinates().tolist()}
Step 2. Geocode and compute distance
map6 = Map("Redlands, CA")
map6
esri_buffer_geom = Geometry(esri_buffer_f_geom_dict)
esri_buffer_geom.extent
(-117.295695233, 33.9560864, -117.09569523299999, 34.1560864)
from arcgis.map.symbols import SimpleFillSymbolEsriSFS, SimpleLineSymbolEsriSLS, SimpleFillSymbolStyle, PictureMarkerSymbolEsriPMS
fill_symbol = SimpleFillSymbolEsriSFS(
color=[255,0,0,100],
style=SimpleFillSymbolStyle.esri_sfs_null,
outline=SimpleLineSymbolEsriSLS(
color=[0,0,0,255],
width=1
))
map6.content.draw(esri_buffer_geom, symbol=fill_symbol)
star_symbol = PictureMarkerSymbolEsriPMS(
angle=0,
xoffset=0,
yoffset=0,
url="http://static.arcgis.com/images/Symbols/Shapes/RedStarLargeB.png",
contentType="image/png",
width=24,
height=24
)
map6.content.draw(esri_geom.geometry, symbol=star_symbol)
search_area_extent = { 'xmin': esri_buffer_geom.extent[0],
'ymin': esri_buffer_geom.extent[1],
'xmax': esri_buffer_geom.extent[2],
'ymax': esri_buffer_geom.extent[3],
'spatialReference': {'latestWkid': 4326, 'wkid': 102100}}
hospitals = geocode('hospital', search_extent=search_area_extent, max_locations=50)
len(hospitals)
24
hospital_symbol = PictureMarkerSymbolEsriPMS(
angle=0,
xoffset=0,
yoffset=0,
url="http://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png",
contentType="image/png",
width=24,
height=24
)
neighborhood_data_dict = {}
neighborhood_data_dict['hospitals'] = []
for place in hospitals:
place['location'].update({"spatialReference" : {"wkid" : 4326}})
popup=PopupInfo(**{"title" : place['attributes']['PlaceName'],
"description" : place['attributes']['Place_addr']})
map6.content.draw(place['location'], symbol=hospital_symbol, popup=popup)
neighborhood_data_dict['hospitals'].append(place['attributes']['PlaceName'])
for place in hospitals:
print(place["location"])
{'x': -117.196766177888, 'y': 34.108191331266, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.194836431779, 'y': 34.135694787075, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.194836479629, 'y': 34.135694757465, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.195432903971, 'y': 34.121581106134, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.220569945935, 'y': 34.048283738392, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.25241592665, 'y': 34.050235512268, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.252356430406, 'y': 34.047383376877, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.243677086826, 'y': 34.063384148104, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.261122200373, 'y': 34.049504416919, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.26567905278, 'y': 34.050524217791, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.261122141553, 'y': 34.049369351607, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.205019353286, 'y': 34.037157571828, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.214470871989, 'y': 34.048694352034, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.217167206134, 'y': 34.061966615667, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.255487610658, 'y': 34.104516812661, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.278761323128, 'y': 34.134917592562, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.278760385857, 'y': 34.134472458815, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.278465929599, 'y': 34.13489096724, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.27616503598, 'y': 34.1359064912, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.277012707438, 'y': 34.135915708772, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.285191602008, 'y': 34.067766367944, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.285188057476, 'y': 34.068724, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.278795482457, 'y': 34.078829, 'spatialReference': {'wkid': 4326}, 'type': 'point'} {'x': -117.19435582209, 'y': 34.135812141583, 'spatialReference': {'wkid': 4326}, 'type': 'point'}
from arcgis.geometry import Point, distance
neighborhood_data_dict['distance'] = []
for place in hospitals:
dis = distance(
spatial_ref=4326,
geometry1=Point(place["location"]),
geometry2=esri_geom.geometry,
geodesic=False,
gis=gis)
neighborhood_data_dict['distance'].append(dis['distance'])
Step 3. Present results in tables and bar charts
Note: The distance column is to displayed in units of 100 miles.
import pandas as pd
neighborhood_df = pd.DataFrame.from_dict(neighborhood_data_dict, orient='index')
neighborhood_df = neighborhood_df.transpose()
neighborhood_df
hospitals | distance | |
---|---|---|
0 | Lindora Clinic | 0.052116 |
1 | Wound Healing Center - St. Bernardine Medical ... | 0.079613 |
2 | Dignity Health Urgent Care - Highland | 0.079613 |
3 | Dignity Health Medical Group - Inland Empire | 0.065495 |
4 | Loma Linda Surgical Hospital | 0.02607 |
5 | VA Loma Linda Medical Center | 0.057022 |
6 | Loma Linda University Medical Center East Camp... | 0.057326 |
7 | Select Physical Therapy | 0.048534 |
8 | Loma Linda University Medical Center | 0.065757 |
9 | Loma Linda University Health | 0.070205 |
10 | Loma Linda University Children's Hospital | 0.065771 |
11 | Redlands Community Hospital | 0.021101 |
12 | Loma Linda University Behavioral Medical Center | 0.020178 |
13 | Aegis Treatment Centers | 0.022263 |
14 | Mfi Recovery Center | 0.076946 |
15 | Dignity Health Medical Group - Inland Empire | 0.114518 |
16 | St Bernardine Medical Center | 0.114211 |
17 | Emergency Services - St. Bernardine Medical Ce... | 0.114285 |
18 | Dignity Health Medical Group - Inland Empire | 0.113343 |
19 | Baby And Family Center at St. Bernardine Medic... | 0.113953 |
20 | Planned Parenthood - San Bernardino Health Center | 0.090255 |
21 | Inland Pain Medicine | 0.090381 |
22 | Sygnus Desendant | 0.086156 |
23 | Dignity Health Medical Group - Inland Empire | 0.079737 |
The bar plot below displays the real address on the x-axis for each entry of hospitals on the x-axis.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
addrs = neighborhood_data_dict["hospitals"]
scores = neighborhood_data_dict["distance"]
ax.bar(addrs,scores)
plt.xticks(rotation=90)
plt.show()
Finding POIs using category filtering
We have seen selective examples with the category
parameter being used in the geocode()
function above. The steps below show the users how to get the list of all categories the geocoder knows and some usage examples:
Get a list of available categories and sub-categories with the current geocoder
from arcgis.geocoding import get_geocoders
geocoder = get_geocoders(gis)[0]
def list_categories(obj, depth = 0):
for category in obj['categories']:
print('\t'*depth + category['name'])
if 'categories' in category:
list_categories(category, depth + 1)
list_categories(geocoder.properties)
Address Subaddress Point Address Street Address Distance Marker Intersection Street Midblock Street Between Street Name Postal Primary Postal Postal Locality Postal Extension Coordinate System LatLong XY YX MGRS USNG Populated Place Block Sector Neighborhood District City Metro Area Subregion Region Territory Country Zone POI Arts and Entertainment Amusement Park Aquarium Art Gallery Art Museum Billiards Bowling Alley Casino Cinema Historical Monument History Museum Indoor Sports Jazz Club Landmark Library Live Music Museum Other Arts and Entertainment Performing Arts Ruin Science Museum Tourist Attraction Wild Animal Park Zoo Education College Fine Arts School Other Education School Vocational School Food African Food American Food Argentinean Food Australian Food Austrian Food Bakery Balkan Food BBQ and Southern Food Belgian Food Bistro Brazilian Food Breakfast Brewpub British Isles Food Burgers Cajun and Creole Food Californian Food Caribbean Food Chicken Restaurant Chilean Food Chinese Food Coffee Shop Continental Food Creperie East European Food Fast Food Filipino Food Fondue French Food Fusion Food German Food Greek Food Grill Hawaiian Food Ice Cream Shop Indian Food Indonesian Food International Food Irish Food Italian Food Japanese Food Korean Food Kosher Food Latin American Food Malaysian Food Mexican Food Middle Eastern Food Moroccan Food Other Restaurant Pastries Pizza Polish Food Portuguese Food Restaurant Russian Food Sandwich Shop Scandinavian Food Seafood Snacks South American Food Southeast Asian Food Southwestern Food Spanish Food Steak House Sushi Swiss Food Tapas Thai Food Turkish Food Vegetarian Food Vietnamese Food Winery Land Features Atoll Basin Butte Canyon Cape Cave Cliff Continent Desert Dune Flat Forest Glacier Grassland Hill Island Isthmus Lava Marsh Meadow Mesa Mountain Mountain Range Oasis Other Land Feature Peninsula Plain Plateau Point Ravine Ridge Rock Scrubland Swamp Valley Volcano Wetland Nightlife Spot Bar or Pub Dancing Karaoke Night Club Nightlife Parks and Outdoors Basketball Beach Campground Diving Center Fishing Garden Golf Course Golf Driving Range Hockey Ice Skating Rink Nature Reserve Other Parks and Outdoors Park Racetrack Scenic Overlook Shooting Range Ski Lift Ski Resort Soccer Sports Center Sports Field Swimming Pool Tennis Court Trail Wildlife Reserve Professional and Other Places Ashram Banquet Hall Border Crossing Building Business Facility Cemetery Church City Hall Civic Center Convention Center Court House Dentist Doctor Embassy Factory Farm Fire Station Government Office Gurdwara Hospital Industrial Zone Insurance Livestock Medical Clinic Military Base Mine Mosque Observatory Oil Facility Orchard Other Professional Place Other Religious Place Pagoda Place of Worship Plantation Police Station Post Office Power Station Prison Public Restroom Radio Station Ranch Recreation Facility Religious Center Scientific Research Shrine Storage Synagogue Telecom Temple Tower Veterinarian Vineyard Warehouse Water Tank Water Treatment Residence Estate House Nursing Home Residential Area Shops and Service ATM Auto Dealership Auto Maintenance Auto Parts Bank Beauty Salon Beauty Supplies Bookstore Butcher Candy Store Car Wash Childrens Apparel Clothing Store Consumer Electronics Store Convenience Store Delivery Service Department Store Electrical Fitness Center Flea Market Food and Beverage Shop Footwear Furniture Store Gas Station Grocery Home Improvement Store Jewelry Laundry Market Mens Apparel Mobile Phone Shop Motorcycle Shop Office Supplies Store Optical Other Shops and Service Pet Store Pharmacy Plumbing Repair Services Shopping Center Spa Specialty Store Sporting Goods Store Tire Store Toy Store Used Car Dealership Wholesale Warehouse Wine and Liquor Womens Apparel Yoga Studio Travel and Transport Airport Bed and Breakfast Bridge Bus Station Bus Stop Cargo Center Dock EV Charging Station Ferry Heliport Highway Exit Hostel Hotel Marina Metro Station Motel Other Travel Parking Pier Port Railyard Rental Cars Resort Rest Area Taxi Tollbooth Tourist Information Train Station Transportation Service Travel Agency Truck Stop Tunnel Weigh Station Water Features Abyssal Plain Bay Canal Channel Continental Rise Continental Shelf Continental Slope Cove Dam Delta Estuary Fjord Fracture Zone Gulf Harbor Hot Spring Irrigation Jetty Lagoon Lake Ocean Ocean Bank Oceanic Basin Oceanic Plateau Oceanic Ridge Other Water Feature Reef Reservoir Sea Seamount Shoal Sound Spring Strait Stream Submarine Canyon Submarine Cliff Submarine Fan Submarine Hill Submarine Terrace Submarine Valley Trench Undersea Feature Waterfall Well Wharf
An example of finding restaurants around a given location
Now let us find restaurants near Time Square (with a maximum of returned results set to 100, since there are way too many restaurants in the specified location).
time_square = geocode("Time Square, NYC")[0]
map8 = Map("Time Square, NYC")
map8
map8.center = [40.7575 , -73.9855]
restaurants = geocode(None, time_square['extent'], category="Food", max_locations=100)
for restaurant in restaurants:
popup = PopupInfo(**{
"title" : restaurant['address'],
"description" : "Phone: " + restaurant['attributes']['Phone']
})
restaurant['location'].update({"spatialReference" : {"wkid" : 4326}})
map8.content.draw(restaurant['location'], popup)
How to refine the results by sub-category
Still using the last request to search for restaurants near Time Square, we will further refine the search by sub-categories, e.g. Indian, Chinese, Burgers, Thai.. etc.
The category
parameter is used to specify a place or address type which can be used to filter results. The parameter supports input of single category values
or multiple comma-separated values
. Its usage (shown below) is applicable for all other categories that have sub-categories, besides food. For instance, Education
would include College
, Fine Arts School
, Other Education
, School
and Vocational School
. For more categories and sub-categories, please refer to API Reference.
map9 = Map("Time Square, NYC")
map9
categories = "Indian Food, Chinese Food, Burgers, Thai Food"
chinese_symbol = SimpleMarkerSymbolEsriSMS(
style=SimpleMarkerSymbolStyle.esri_sms_square,
color=[115,100,76,55],
size=8,
angle=0,
xoffset=0,
yoffset=0,
outline=SimpleLineSymbolEsriSLS(
color=[152,230,0,255],
width=1
))
burgers_symbol = SimpleMarkerSymbolEsriSMS(
style=SimpleMarkerSymbolStyle.esri_sms_circle,
color=[15,0,176,255],
size=8,
angle=0,
xoffset=0,
yoffset=0,
outline=SimpleLineSymbolEsriSLS(
color=[152,230,0,255],
width=1
))
restaurants = geocode(None, time_square['extent'], category=categories, max_locations=100)
for restaurant in restaurants:
restaurant['location'].update({"spatialReference" : {"wkid" : 4326}})
popup = PopupInfo(**{
"title" : restaurant['address'],
"content" : "Phone: " + restaurant['attributes']['Phone']
})
if restaurant['attributes']['Type'] == 'Thai Food':
map9.content.draw(restaurant['location'], popup, thai_symbol) # green square
elif restaurant['attributes']['Type'] == 'Indian Food':
map9.content.draw(restaurant['location'], popup, indian_symbol) # dark red circle
elif restaurant['attributes']['Type'] == 'Chinese Food':
map9.content.draw(restaurant['location'], popup, chinese_symbol) # mint square
else:
map9.content.draw(restaurant['location'], popup, burgers_symbol) # blue circle
Example of finding gas stations, bars, and other facilities near a given location
The example below showcases how to find gas stations, bars, libraries, schools, parks, and grocery stores around a given location, based on the previous sample in which we look for hospitals near Esri Headquarter.
Step 1. Create symbols for facilities
symbols = {"groceries": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/PeoplePlaces/Shopping.png",
"contentType":"image/png","width":12,"height":12}),
"coffee": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/PeoplePlaces/Coffee.png",
"contentType":"image/png","width":12,"height":12}),
"restaurant": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/PeoplePlaces/Dining.png",
"contentType":"image/png","width":12,"height":12}),
"bar": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/PeoplePlaces/Bar.png",
"contentType":"image/png","width":12,"height":12}),
"gas": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/Transportation/esriBusinessMarker_72.png",
"contentType":"image/png","width":12,"height":12}),
"park": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/OutdoorRecreation/RestArea.png",
"contentType":"image/png","width":10,"height":10}),
"school": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/PeoplePlaces/Note.png",
"contentType":"image/png","width":10,"height":10}),
"library": PictureMarkerSymbolEsriPMS(**{"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/PeoplePlaces/LiveShow.png",
"contentType":"image/png","width":12,"height":12})}
list(symbols.keys())
['groceries', 'coffee', 'restaurant', 'bar', 'gas', 'park', 'school', 'library']
Step 2. Define your own geocode function
Next, let's define a function to use the ArcGIS Geocoding service in search of facilities around the Esri Headquarter, based on the kind of facilities (e.g. groceries) you are looking for:
def search_and_map(in_map, kind="groceries"):
per_kind = geocode(kind, search_extent=search_area_extent,
max_locations=20, as_featureset=True)
neighborhood_data_dict[kind] = []
for place in per_kind:
popup=PopupInfo(**{"title" : place.attributes['PlaceName'],
"description" : place.attributes['Place_addr']})
in_map.content.draw(place.geometry, symbol=symbols[kind], popup=popup)
neighborhood_data_dict[kind].append(place.attributes['PlaceName'])
Now, we are ready to loop through the list of facility types and perform geocoding for each kind, then map the results with the customized symbols:
map7 = Map("Redlands, CA")
map7
map7.zoom = 13
for kind in list(symbols.keys()) :
search_and_map(map7, kind)
Step 3. Tabularize the results
Last but not least, let's present the results in a table:
neighborhood_df = pd.DataFrame.from_dict(neighborhood_data_dict, orient='index')
neighborhood_df = neighborhood_df.transpose()
neighborhood_df
hospitals | distance | groceries | coffee | restaurant | bar | gas | park | school | library | |
---|---|---|---|---|---|---|---|---|---|---|
0 | Lindora Clinic | 0.052116 | Stater Bros. Markets | Starbucks | Rock Coffee | Third Street Tavern | C A R Enterprises | Shadow Mountain Park | Vista Heights Middle School | Highland Sam J. Racadio Library & Environmenta... |
1 | Wound Healing Center - St. Bernardine Medical ... | 0.079613 | Stater Bros. Markets | Starbucks | Keke's Taco Stand | The Green Frog | Shell Oil | Gateway Park | Sugar Hill Elementary School | San Bernardino County Library - Loma Linda |
2 | Dignity Health Urgent Care - Highland | 0.079613 | ALDI | Starbucks | Steves Burger | The Belle | Pilot Flying J | Box Springs Regional Park | Mentone Elementary School | Loma Linda Branch Public Library |
3 | Dignity Health Medical Group - Inland Empire | 0.065495 | Food 4 Less | Starbucks | Armandos Sunnymead | Joy's Lounge | Food'n Fuel | Rich Dauer Pine Park | Arrowhead Christian Academy | Loma Linda City Library |
4 | Loma Linda Surgical Hospital | 0.02607 | F & T Market | Starbucks | Saucedo Asadero Campestre | Lobby Bar | ARCO | Leonard Bailey Park | Cope Middle School | Llu Del E Webb Memorial Library |
5 | VA Loma Linda Medical Center | 0.057022 | Albertsons | Boba Tea House | Maria's Cafe Mexican Restaurant | The 909 | Chevron Extra Mile | Hulda Crooks Park | Kingsbury Elementary School | Mentone Library & Senior Center |
6 | Loma Linda University Medical Center East Camp... | 0.057326 | Stater Bros. Markets | Dutch Bros Coffee | El Mushasho Alegre Mariscos | George Lopez's Chingon Kitchen | Shell Oil | Loma Linda Community Park | Serrano Middle School | University of Redlands - George & Verda Armaco... |
7 | Select Physical Therapy | 0.048534 | Smart & Final | Starbucks | Funnel Cake Friday's | The Beach House | 76 | Mission Creek Park | Lankershim Elementary School | Armacost Library |
8 | Loma Linda University Medical Center | 0.065757 | Clark's Nutritional Center Inc | Starbucks | Cheliz Restaurant | The Blue Bar | Propane Refill | Redlands Community Park | Warm Springs Elementary School | Ak Smiley Public Library |
9 | Loma Linda University Health | 0.070205 | Dhaka Sweets Spices | The Coffee Bean & Tea Leaf | Denny's | Diamond Jim's Saloon | Mobil | Sylvan Park | Bryn Mawr Elementary School | River Christian Reformed Church Library |
10 | Loma Linda University Children's Hospital | 0.065771 | Stater Bros. Markets | Starbucks | American Legion | The Boiler Room | Chevron | Texonia Park | Crafton Elementary School | Howard M. Rowe Branch Library |
11 | Redlands Community Hospital | 0.021101 | Trader Joe's | Starbucks | Pepper Steak Restaurant | Vapor Squad Smoke Shop | Valero Energy | The Terrace | Moore Middle School | Inland Library System |
12 | Loma Linda University Behavioral Medical Center | 0.020178 | Vons | Starbucks | The Burger Boys | The Pink Flamingo | ARCO | Ford Park | Kimberly Elementary School | Law Library For San Bernardino County |
13 | Aegis Treatment Centers | 0.022263 | Sprouts Farmers Market | Starbucks | Bear Springs Bistro & Lounge | Absent 9 | Valero Energy | Caroline Park | Aquinas High School | San Bernardino Symphony Guthrie Library |
14 | Mfi Recovery Center | 0.076946 | ALDI | Starbucks | Armando's Mexican Food | Club Evo | Chevron | Ed Hales Park | Sierra High School | Argosy University - San Bernardino Library |
15 | Dignity Health Medical Group - Inland Empire | 0.114518 | Stater Bros. Markets | Starbucks | Del Taco | Empire Bowl | Chevron Extra Mile | Smiley Park | Childrens Depot | Crafton Hills College Library |
16 | St Bernardine Medical Center | 0.114211 | IGA | Starbucks | Oishii Sushi & Teriyaki | Black Antler Book Club | 7-Eleven Fuel | Brookside Park | Harris Family WeeCare | Highland Branch San Bernardino County Library |
17 | Emergency Services - St. Bernardine Medical Ce... | 0.114285 | Stater Bros. Markets | Starbucks | Jack in the Box | The Vault | ARCO | Mission Gables | Adams Family Daycare & Preschl | Loma Linda Branch San Bernardino County Library |
18 | Dignity Health Medical Group - Inland Empire | 0.113343 | Albertsons | Starbucks | The Cupcake & Espresso Bar | Vault Martini Bar & Grill | Valero Energy | Prospect Park | Hidden Springs Elementary School | Del E Webb Memorial Library |
19 | Baby And Family Center at St. Bernardine Medic... | 0.113953 | Stater Bros. Markets | Starbucks | Deserved Sweets By | Karaoke Kubo | Chevron | Meadowbrook Park | Country Day School | Mentone Branch San Bernardino County Library |
20 | Planned Parenthood - San Bernardino Health Center | 0.090255 | None | None | None | None | None | None | None | None |
21 | Inland Pain Medicine | 0.090381 | None | None | None | None | None | None | None | None |
22 | Sygnus Desendant | 0.086156 | None | None | None | None | None | None | None | None |
23 | Dignity Health Medical Group - Inland Empire | 0.079737 | None | None | None | None | None | None | None | None |
neighborhood_df.count().plot(kind='bar')
plt.title('Facilities within 10 miles of Esri')
Text(0.5, 1.0, 'Facilities within 10 miles of Esri')
Conclusions
In Part 3, we have walked through different user scenarios using the category
parameter within the geocode()
function to search and filter geocoded results. In the last scenario, because home buyers often look for access to facilities, such as groceries, restaurants, schools, emergency, and health care, near prospective neighborhoods when shortlisting properties, we used the geocoding
module to search for these facilities, build a table for each property, and map the deliverables.