Javascript XML parsing for GML and you

You find the need to determine the locations of your visitors, and you wonder how to do this? Surely it's impossible. Alas, it is not. Services like HostIP provide the ability to locate your users given their IP address. The slick way to do this is via javascript. Unfortunately, the HostIP API doesn't provide a JSON interface.

But of course, the response is in XML, so you're also wondering how to parse this XML response for something meaningful? The answer is the DOMParser and namespaces. There is a really nice function, getElementsByTagNameNS that allows you to parse out elements given a namespace. I kept trying getElementsByTagNameNS("gml","name"), which didn't work. The answer seems to be that you need to include a valid uri for the namespace.

var dom = new DOMParser ( ) .parseFromString ( responseText,
"application/xml" ) ;

var location = dom.getElementsByTagNameNS (
"", "name" ) [1]
if location == " ( Unknown city ) "
return "";

About this article

written on
posted in ProgrammingGeolocationJavascriptHowto Back to Top

About the Author

Andrew Turner is an advocate of open standards and open data. He is actively involved in many organizations developing and supporting open standards, including OpenStreetMap, Open Geospatial Consortium, Open Web Foundation, OSGeo, and the World Wide Web Consortium. He co-founded CrisisCommons, a community of volunteers that, in coordination with government agencies and disaster response groups, build technology tools to help people in need during and after a crisis such as an earthquake, tsunami, tornado, hurricane, flood, or wildfire.