Obtaining Client Geo Location Information
This example captures HTTP requests and responds with the user's geo location information, to generate an HTML page containing the autonomous system number (ASN), country, region, city, longitude and latitude information. It can be used for debugging or displaying the geo location information.
Sample Code
// Add a fetch event listener, which is triggered when a request is incoming. It uses the handleRequest function to handle requests and return responses.addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});// Define an async function handleRequest, which is used to handle the incoming requests.async function handleRequest(request) {// Initialize an empty string to store the HTML content.let html_content = "";// Define the HTML style.let html_style = "body{padding:6em; font-family: sans-serif;} h1{color:#0000ff;}";// Get the user's geo location information.html_content += "<p> asn: " + request.eo.geo.asn + "</p>"; // ASNhtml_content += "<p> countryName: " + request.eo.geo.countryName + "</p>"; // Country namehtml_content += "<p> countryCodeAlpha2: " + request.eo.geo.countryCodeAlpha2 + "</p>"; // Alpha-2 country codehtml_content += "<p> countryCodeAlpha3: " + request.eo.geo.countryCodeAlpha3 + "</p>"; // Alpha-3 country codehtml_content += "<p> countryCodeNumeric: " + request.eo.geo.countryCodeNumeric + "</p>"; // Numeric country codehtml_content += "<p> regionName: " + request.eo.geo.regionName + "</p>"; // Region namehtml_content += "<p> regionCode: " + request.eo.geo.regionCode + "</p>"; // Region codehtml_content += "<p> cityName: " + request.eo.geo.cityName + "</p>"; // City namehtml_content += "<p> Latitude: " + request.eo.geo.latitude + "</p>"; // Latitudehtml_content += "<p> Longitude: " + request.eo.geo.longitude + "</p>"; // Longitude// Construct the HTML response content.let html = `<!DOCTYPE html><head><title> Geolocation: Hello World By Edge Functions.</title><style> ${html_style} </style></head><body><h1>Geolocation: Hello World By Edge Functions.</h1><p> Welcome to try out the geolocation feature of Edge Functions.</p>${html_content}</body>`;// Return a new Response object, including the HTML content and corresponding headers.return new Response(html, {headers: {"content-type": "text/html;charset=UTF-8", // Set the Content-Type header of the response, specifying the returned content as HTML.},});}
Sample Preview
In the address bar of the browser, enter a URL that matches a triggering rule of the edge function to preview the effect of the sample code.
Related References