domingo, 16 de septiembre de 2018

PHP: Get Latitude/Longitude using Google Maps API


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$address = "Kathmandu, Nepal";
$url = "http://maps.google.com/maps/api/geocode/json?address=".urlencode($address);
<!--more-->
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$responseJson = curl_exec($ch);
curl_close($ch);
$response = json_decode($responseJson);
if ($response->status == 'OK') {
    $latitude = $response->results[0]->geometry->location->lat;
    $longitude = $response->results[0]->geometry->location->lng;
    echo 'Latitude: ' . $latitude;     
    echo '<br />';     
    echo 'Longitude: ' . $longitude;
} else {
    echo $response->status;
    var_dump($response);
    exit;
}

Display Google Map with Marker using Latitude & Longitude Coordinates

    <head>
        <title>Google Map</title>
        <meta name="viewport" content="initial-scale=1.0">
        <meta charset="utf-8">
        <style>          
          #map {
            height: 300px;    
            width: 600px;            
          }          
        </style>        
    </head>    
    <body>        
        <div style="padding:10px">
            <div id="map"></div>
        </div>
        
        <script type="text/javascript">
        var map;
        
        function initMap() {                            
            var latitude = 27.7172453; // YOUR LATITUDE VALUE
            var longitude = 85.3239605; // YOUR LONGITUDE VALUE
            
            var myLatLng = {lat: latitude, lng: longitude};
            
            map = new google.maps.Map(document.getElementById('map'), {
              center: myLatLng,
              zoom: 14                    
            });
                    
            var marker = new google.maps.Marker({
              position: myLatLng,
              map: map,
              //title: 'Hello World'
              
              // setting latitude & longitude as title of the marker
              // title is shown when you hover over the marker
              title: latitude + ', ' + longitude
            });            
        }
        </script>
        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap"
        async defer></script>
    </body>    
</html>