Tag Archives: geocode

ESRI REST API: GeoCoding OR OpenStreet Map

10 Jun

UPDATE: OpenStreet Map code at bottom.


Saw a Tweet saying that the ArcGIS REST API for Geocoding is moving to a new URL. I use Google when I just needed a single Lat,Long and ArcPy to Geocode CSV’s, but I decided to check out the REST API and throw together a Python script from my old Google one – which I got from Foundations of Python Network Programming.

Not much to the script – pass parameters to a URL and grab the JSON. You can go to the HELP for more info about the parameters – like setting outfields=*;

Here is the script (it grabs the first result):

import urllib, urllib2, simplejson
import csv

param = {‘Address’: ‘400 Roma SE’,’City’:’albuquerque’,’Region’:’nm’,’Postal’:’87102′,’outFields’:’location’,’f’:’pjson’}
url = ‘http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?’ + urllib.urlencode(param)
rawreply = urllib2.urlopen(url).read()
reply = simplejson.loads(rawreply)

print “Long: ”
print reply[“candidates”][0][“location”][“x”]

print “Lat: ”
print reply[“candidates”][0][“location”][“y”]


OpenStreet Map is almost the same, just change the URL and the parameters.

import urllib, urllib2, simplejson
import csv

param = {‘q’: ‘400 roma, albuquerque’,’format’:’json’,’addressdetails’:’1′}
url = ‘http://nominatim.openstreetmap.org/search?’ + urllib.urlencode(param)
rawreply = urllib2.urlopen(url).read()
reply = simplejson.loads(rawreply)

print reply[0][“lat”]
print reply[0][“lon”]


Public Safety GIS 2: Python, MongoDB, C# and ArcGIS Desktop Explorer

17 Apr

I wrote a plugin for ArcGIS Desktop explorer that called a python script and passed the map center as an argument. The python script queried a MongoDB and wrote out a csv of closest points. The button then loads the csv as points. I had to do this because I didn’t know how to do it in C#. Well, I figured it out.

Now C# does all the work querying the database and drawing the points. I still have a python script that reads data from a csv export from sharepoint, geocodes it and creates the mongoDB.

Here is my code:


from pymongo import Connection,GEO2D
import urllib, urllib2, simplejson
import csv

data = csv.reader(open(‘C:\Documents and Settings…\myfile.csv’))

for row in data:
combinedaddress=address+”,albuquerque, NM”

param = {‘q’: combinedaddress,’output’: ‘json’, ‘oe’: ‘utf8’}
url = ‘http://maps.google.com/maps/geo?’ + urllib.urlencode(param)
rawreply = urllib2.urlopen(url).read()
reply = simplejson.loads(rawreply)
print reply[‘Placemark’][0][‘Point’][‘coordinates’][0]

except KeyError:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGISExplorer;
using ESRI.ArcGISExplorer.Application;
using ESRI.ArcGISExplorer.Mapping;
using ESRI.ArcGISExplorer.Geometry;
using ESRI.ArcGISExplorer.Data;
using ESRI.ArcGISExplorer.Threading;

using MongoDB;
using MongoDB.Bson;
using MongoDB.Driver.Linq;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace MongoC
public class Button : ESRI.ArcGISExplorer.Application.Button

public override void OnClick()

Folder folderMapItem = new Folder();
MapDisplay mdisp = ESRI.ArcGISExplorer.Application.Application.ActiveMapDisplay;

//use this to change the projections 35,-106
FeatureLayer proj = FeatureLayer.OpenShapefile(“C:\\Documents and Settings…\\forProjection.shp”);
// Path for Windows 7: FeatureLayer proj = FeatureLayer.OpenShapefile(“C:\\Users\\user\\…\\forProjection.shp”);
mdisp.CoordinateSystem2D = proj.CoordinateSystem;
string center = mdisp.Center.ToString();
folderMapItem.Name = “Close To Me”;
string[] c = center.Split(null);
String lon = c[3];
String lat = c[6];

MongoClient client = new MongoClient(); // connect to localhost. Deploy at: “mongodb://ip.of.host:27017”
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase(“rtcc”);

var collection = db.GetCollection<BsonDocument>(“cnau”);

var query = Query.Near(“loc”, double.Parse(c[3]), double.Parse(c[6]));
//var cursor = collection.Find(query); Put this in foreach so dont need it anymore.
foreach (BsonDocument item in collection.Find(query).SetLimit(5))
BsonElement loc = item.GetElement(“loc”);
string g = loc.Value.ToString();
string x = g.Trim(new Char[] { ‘[‘, ‘]’ });
String[] a = x.Split(‘,’);
// BsonElement name = item.GetElement(“name”); Work for all indexes in MongoDB
// Pass the other data to the notes popups below

ESRI.ArcGISExplorer.Geometry.Point mypoint = new ESRI.ArcGISExplorer.Geometry.Point(double.Parse(a[0]), double.Parse(a[1]));

// Create a Note using the Point geometry.
Note mypointNote = new Note(“MyNote”, mypoint, Symbol.Marker.Pushpin.Orange);

// Populate the Note popup with information about the Point geometry using the ToString method.
StringBuilder info = new StringBuilder(@”<p><a href=””http://google.com””>Google</a></p>&#8221;);
info.AppendLine(@”<p>” + mypoint.ToString() + @”</p>”);

//MapDisplay disp = ESRI.ArcGISExplorer.Application.Application.ActiveMapDisplay;
mypointNote.Popup.Content = info.ToString();

// Add the Note to the current Map.


Python Function to Geocode an Address Using Google

7 Feb

I stole this from a python networking book – a great book!!- and made it into a function by allowing the user to enter an address and with a return value array contains the longitude and latitude. Enter an address in the format STREET, CITY,STATE ABBREVIATION:

>>>Import google
Address: 100 10th st, Albuquerque,nm
>>>A[0] # returns the longitude
>>>A[1] # returns the latitude

Here is the function-I saved it as google.py:

import urllib, urllib2, json

def latlong():
param = {‘q’: address,’output’: ‘json’, ‘oe’: ‘utf8’}
url = ‘http://maps.google.com/maps/geo?&#8217; + urllib.urlencode(param)
rawreply = urllib2.urlopen(url).read()
reply = json.loads(rawreply)
return a