1<?php
2$address = "Kathmandu, Nepal";
3$url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&key=apikey';
4
5$ch = curl_init();
6curl_setopt($ch, CURLOPT_URL, $url);
7curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
8$responseJson = curl_exec($ch);
9curl_close($ch);
10
11$response = json_decode($responseJson);
12
13if ($response->status == 'OK') {
14 $latitude = $response->results[0]->geometry->location->lat;
15 $longitude = $response->results[0]->geometry->location->lng;
16
17 echo 'Latitude: ' . $latitude;
18 echo '<br />';
19 echo 'Longitude: ' . $longitude;
20} else {
21 echo $response->status;
22 var_dump($response);
23}
24?>
1
2
3<!DOCTYPE html>
4
5<html>
6
7<form method="post">
8
9<input type="text" name="address">
10
11<input type="submit" name="submit" value="submit">
12
13</form>
14
15</html>
16
17<?php
18
19if(isset($_POST['submit']))
20
21{
22
23
24function getLatLong($address){
25
26 if(!empty($address)){
27
28 //Formatted address
29
30 $formattedAddr = str_replace(' ','+',$address);
31
32 //Send request and receive json data by address
33
34 $geocodeFromAddr = file_get_contents
35('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false');
36
37 $output = json_decode($geocodeFromAddr);
38
39 //Get latitude and longitute from json data
40
41 $data['latitude'] = $output->results[0]->geometry->location->lat;
42
43 $data['longitude'] = $output->results[0]->geometry->location->lng;
44
45 //Return latitude and longitude of the given address
46
47 if(!empty($data)){
48
49 return $data;
50
51 }else{
52
53 return false;
54
55 }
56
57 }else{
58
59 return false;
60
61 }
62
63}
64
65$address = $_POST['address'];
66
67$latLong = getLatLong($address);
68
69$latitude = $latLong['latitude']?$latLong['latitude']:'Not found';
70
71$longitude = $latLong['longitude']?$latLong['longitude']:'Not found';
72
73echo "Latitude:".$latitude."<br>";
74
75echo "longitude:".$longitude."";
76
77}
78
79?>
80