October 23, 2024
Chicago 12, Melborne City, USA
jQuery

How to display user location on my website?


I have the following code which is supposed to find the users location and display information about whether the user is in an area where delivery is possible

The code I wrote does not find an accurate position for the users location.

jQuery(document).ready(function($) {
  var serviceAreas = [
    { city: "Mumbai", state: "Maharashtra", pin: "400001" },
    { city: "Delhi", state: "Delhi", pin: "110001" },
    { city: "Bengaluru", state: "Karnataka", pin: "560001" },
    { city: "Hyderabad", state: "Telangana", pin: "500001" },
    { city: "Chennai", state: "Tamil Nadu", pin: "600001" },
    { city: "Nainital", state: "Uttarakhand", pin: "263001" },
    { city: "Haldwani", state: "Uttarakhand", pin: "263139" },
    { city: "Kaladhungi", state: "Uttarakhand", pin: "263140" },
    { city: "Gurugram", state: "Haryana", pin: "122001" },
    { city: "Jaipur", state: "Rajasthan", pin: "302001" },
  ];


  function isServiceAvailable(zip) {
    return serviceAreas.some(function(area) {
      return area.pin === zip;
    });
  }

  function getUserLocation() {
    $.get("https://ipapi.co/json/", function(response) {
      var userZip = response.postal;
      var userCity = response.city;
      var userState = response.region;

      if (isServiceAvailable(userZip)) {
        $('#service-message').html('Great news! We are serving in ' + userCity + ',
        ' + userState + ' (ZIP: ' + userZip + ').');
      } else {
        $('#service-message').html('Unfortunately, we are not serving in ' + userCity + ', ' + userState + ' (ZIP: ' + userZip + ') at this time.');
      }
    }, "json");
  }

  // Display the service area message on page load
  getUserLocation();
});



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video