Validate Latitude and Longitude with regex and php

There are times when you need to validate latitude and longitude coordinates. May be you are taking it as user input or from some other source.

So here are two simple functions to validate latitude and longitude coordinates.
Regular expressions are used to match coordinates and php to check if it is valid or not.

Function to validate latitude


  function isValidLatitude($latitude){
    if (preg_match("/^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}$/", $latitude)) {
        return true;
    } else {
        return false;
    }
  }
 
 # Call function
 
  if (isValidLatitude('28.6100')) {
       echo "Valid Latitude";
  }

Function to validate longitude


  function isValidLongitude($longitude){
    if(preg_match("/^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}$/",
      $longitude)) {
       return true;
    } else {
       return false;
    }
  }

 # Call function
 
  if (isValidLongitude('77.2300')) {
       echo "Valid Longitude";
  }


Validate Latitude and Longitude with regex and php Validate Latitude and Longitude with regex and php Reviewed by JS Pixels on November 15, 2013 Rating: 5

6 comments:

  1. Hello Altaf, I liked your blog and nominated you for a blogger award called liebster Award, (you might have nominated by others as well). The award works like a chain letter where bloggers answer 10 questions abt themselves and nominate 10 more bloggers to answer a new set of 10 questions. you can check the process to complete this chain at below link
    http://priteshdubey.blogspot.in/2013/11/liebster-award.html

    ReplyDelete
  2. Cool! Thank you!!

    A smaller version could be:

    https://gist.github.com/filippomangione/6f9d78e955ae2f228d28

    ReplyDelete
  3. Thanks for the solution!
    But it doesn't validate for latitude - 90.09 (-90 to +90)
    also doesn't validate for longitude - 180.0099 (-180 to +180)

    ReplyDelete
  4. this is not correct plz try this one.

    function isValidLongitude($longitude){
    if(preg_match("/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/",$longitude)) {
    return true;
    } else {
    return false;
    }
    }
    function isValidLatitude($latitude){

    if (preg_match("/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/", $latitude)) {
    return true;
    } else {
    return false;
    }
    }

    ReplyDelete
    Replies
    1. Great answer !! Thanks a lot

      Daniel Badillo 1976a2013DGB

      Delete
  5. hello Altaf your binary left and right code count logic is very good.
    Thanks for the solution!

    ReplyDelete

Altaf Web. Powered by Blogger.