Get Geolocation Data by IP Address

Description

Use the following code to get geolocation data by IP Address of the visitor. You can use this page in a widget, vtl file, container, template, etc.

Code

${esc.h}${esc.h}Get Geolocation information from IP address
${esc.h}set(${esc.d}geolocationFromSession = ${esc.d}session.getAttribute("geolocation"))
${esc.h}if(!${esc.d}UtilMethods.isSet(${esc.d}geolocationFromSession))
    ${esc.h}set(${esc.d}locationURL = "http://www.geoplugin.net/json.gp?ip=${esc.d}request.getRemoteAddr()")
    ${esc.h}set(${esc.d}geolocation = ${esc.d}json.fetch("${esc.d}!locationURL"))
    ${esc.d}session.setAttribute("geolocation", ${esc.d}geolocation)
${esc.h}else
    ${esc.h}set(${esc.d}geolocation = ${esc.d}session.getAttribute("geolocation"))
${esc.h}end

${esc.h}${esc.h} prints out the city and state nearest your ip address

<b>City:</b> ${esc.d}geolocation.geoplugin_city<br>
<b>Country:</b> ${esc.d}geolocation.geoplugin_countryCode<br>

${esc.h}${esc.h} Returns ALL the geolocation data
${esc.d}geolocation