When developing applications based on Google Maps, it is often necessary to verify coordinates to ensure that they comply with the prescribed format on the map. And the best way to verify coordinates is to use regular expressions. In this article, we will explain how to validate Google Maps coordinates using PHP regular expressions.
The coordinate format on Google Maps is usually "Latitude, Longitude" (Latitude, Longitude), formally using degrees (°), Minutes (′) and seconds (″). So their format is usually like this:
Latitude: Degrees.Minutes and seconds
Longitude: Degrees.Minutes and seconds
For example, The coordinates of New York City are 40.7128°N, 74.0060°W. This coordinate can be written in the following way:
Latitude: 40°42′46.1″N
Longitude: 74°00′21.6″W
In order to verify Google Maps coordinates, we need to use a regular expression that can match coordinates in the above format. Here is this regular expression:
/^[- ]?([1-8]?d(.d )?|90(.0 )?),s*[- ]?(180(.0 )?|((( 1[0-7]d)|([1-9]?d))(.d )?)$/
This expression can match the following types of coordinates:
40 °42′46.1″N, 74°00′21.6″W
-33.86, 151.20
The symbols in the expression have the following meanings:
Once we have this regular expression, validating coordinates is simple. Here is some sample code:
function validate_coordinate($coordinate) {
29f2d65c7480c8a16c18d447eb72a5c7}
// test the function using valid coordinates
echo validate_coordinate("40°42′46.1″N, 74°00′21.6 "W"); // output: 1
echo validate_coordinate("-33.86, 151.20"); // output: 1
// test the function using an invalid coordinate
echo validate_coordinate( "foobar"); // output: 0
?>
In the above code, we wrote a function called validate_coordinate that uses a regular expression to validate the incoming coordinates parameter. If the coordinates conform to the specified format, 1 is returned; otherwise 0 is returned.
Regular expressions are a simple and effective method that can help us verify the format of Google Maps coordinates. In PHP, we can use the preg_match function to verify whether a string matches a regular expression. Therefore, we can very easily write a function that validates the format of Google Maps coordinates.
The above is the detailed content of PHP regular expression method to verify Google Maps coordinates. For more information, please follow other related articles on the PHP Chinese website!