Подтвердить что ты не робот

Google Maps - преобразование адреса в широту и долготу - PHP backend?

Можно ли преобразовать (в PHP-back-end):

<?php
  $Address = "Street 1, City, Country"; // just normal address
?>

to

<?php
  $LatLng = "10.0,20.0"; // latitude & lonitude
?>

Используемый мной код по умолчанию:

<script type='text/javascript' src='https://maps.googleapis.com/maps/api/js?v=3.exp&#038;sensor=false'></script>

<script>

function initialize() {
  var myLatlng = new google.maps.LatLng(10.0,20.0);
  var mapOptions = {
    zoom: 16,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'This is a caption'
  });
}

google.maps.event.addDomListener(window, 'load', initialize); 

</script>

<div id="map"></div>

Я читал https://developers.google.com/maps/documentation/geocoding какое-то время, но я недостаточно опытен, я думаю.

Спасибо.

4b9b3361

Ответ 1

Это работает для меня:

<?php
  $Address = urlencode($Address);
  $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
  $xml = simplexml_load_file($request_url) or die("url not loading");
  $status = $xml->status;
  if ($status=="OK") {
      $Lat = $xml->result->geometry->location->lat;
      $Lon = $xml->result->geometry->location->lng;
      $LatLng = "$Lat,$Lon";
  }
?>

Литература:

Ответ 2

<?php

/* 
* Given an address, return the longitude and latitude using The Google Geocoding API V3
*
*/

function Get_LatLng_From_Google_Maps($address) {
    $address = urlencode($address);

    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";

    // Make the HTTP request
    $data = @file_get_contents($url);
    // Parse the json response
    $jsondata = json_decode($data,true);

    // If the json data is invalid, return empty array
    if (!check_status($jsondata))   return array();

    $LatLng = array(
        'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],
        'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],
    );

    return $LatLng;
}

/* 
* Check if the json data from Google Geo is valid 
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

Для примера кода, как использовать вышеприведенную функцию, не стесняйтесь посетить мой блог

Ответ 3

Да, вы можете. Вы запросили бы запрос с file_get_contents или curl к URL-адресу, подобному этому:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false

Возвращается json закодированный ответ. Вы можете проанализировать это в массивах с помощью json_decode.

На странице документации есть пример того, как может выглядеть ответ, используйте это, чтобы найти нужные вам данные.

Ответ 4

 this will work please try this one i have tested it .
 <?php
            $address = 'Street 1, City, Country'; // Your address
            $prepAddr = str_replace(' ','+',$address);

            $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');

            $output= json_decode($geocode);

             $lat = $output->results[0]->geometry->location->lat;
             $long = $output->results[0]->geometry->location->lng;

             echo $address.'<br>Lat: '.$lat.'<br>Long: '.$long;

    ?>