【问题标题】:Google places API and URL shortener APIGoogle Places API 和 URL Shorter API
【发布时间】:2018-11-20 07:00:28
【问题描述】:

简介:我正在尝试使用 google Places API 和 URL Shorter API 创建一个网络应用程序。如果用户搜索某个地点,它会提取地点 ID 并创建一个长 URL -“http://search.google.com/local/writereview?placeid=”+place_id”,然后使用此长 URL 使用 Google URL 缩短 API 将其缩短,然后将其填充到文本字段中,以便用户可以复制生成的短 URL。我无法弄清楚为什么它不会缩短 URL。请注意我的实际代码中有 (api_key)。非常感谢任何帮助。

谢谢。

Index.html 代码

<input id="pac-input" class="controls" type="text"
    placeholder="Enter a location">
<div id="map"></div>
<div id="infowindow-content">
  <span id="place-name"  class="title"></span><br>
  Place ID <span id="place-id"></span><br>
  <span id="place-address"></span>
</div>
<br>
<input id="gp_link" class="form-control" type="text" value="" placeholder="Your Google Review Link" readonly >
<br><br>

<script>
  // This sample uses the Place Autocomplete widget to allow the user to search
  // for and select a place. The sample then displays an info window containing
  // the place ID and other information about the place that the user has
  // selected.

  // This example requires the Places library. Include the libraries=places
  // parameter when you first load the API. For example:
  // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">


  jQuery("#gp_link").click(function () {
    jQuery(this).select();
});

function get_short_link(place_id) {
    jQuery.ajax({
        type: "POST",
        url: "curl.php",
        data: "longUrl=http://search.google.com/local/writereview?placeid=" + place_id,
        complete:function(data) {
    alert(data);
            jQuery("#gp_link").val(data);
        }
    });

}

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -33.8688, lng: 151.2195},
      zoom: 13
    });

    var input = document.getElementById('pac-input');

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var infowindow = new google.maps.InfoWindow();
    var infowindowContent = document.getElementById('infowindow-content');
    infowindow.setContent(infowindowContent);
    var marker = new google.maps.Marker({
      map: map
    });
    marker.addListener('click', function() {
      infowindow.open(map, marker);
    });

    autocomplete.addListener('place_changed', function() {
      infowindow.close();
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        return;
      }

      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);
      }

      // Set the position of the marker using the place ID and location.
      marker.setPlace({
        placeId: place.place_id,
        location: place.geometry.location
      });
      marker.setVisible(true);

      infowindowContent.children['place-name'].textContent = place.name;
      infowindowContent.children['place-id'].textContent = place.place_id;
      infowindowContent.children['place-address'].textContent =
          place.formatted_address;
      infowindow.open(map, marker);
      get_short_link(place.place_id);
    });
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=(api_key)&libraries=places&callback=initMap"
    async defer></script>

curl.php 文件

<?php

define('GOOGLE_URL', 'https://www.googleapis.com/urlshortener/v1/url');
define('GOOGLE_API_KEY', 'api key goes here');


if( isset( $_POST[ 'longUrl' ] ) ) {
    echo shorten( $_POST[ 'longUrl' ] );
} elseif( isset( $_GET[ 'shortUrl' ] ) ) {
    echo expand($_GET[ 'shortUrl' ] );
} else {
    echo 'You must enter a URL.';
} // end if/else

/*------------------------------------------*/
/* API Functions
/*------------------------------------------*/

/**
 * Shortens the incoming URL using the Google URL shortener API
 * and returns the shortened version.
 *
 * @long_url    The URL to shorten.
 */
function shorten($long_url) {

    $ch = curl_init(GOOGLE_URL . '?key=' . GOOGLE_API_KEY);

    curl_setopt_array(
        $ch,
        array(
            CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_TIMEOUT => 5,
            CURLOPT_CONNECTTIMEOUT => 0,
            CURLOPT_POST => 1,
            CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_POSTFIELDS => '{"longUrl": "' . $long_url . '"}'
        )
    );

    $json_response = json_decode(curl_exec($ch), true);
    return $json_response['id'] ? $json_response['id'] : $long_url;

} // end shorten
?>

【问题讨论】:

  • 只是一个问题...您是否必须通过 PHP 查询 URL 缩短器?
  • This 可能值得一读,因为 URL 缩短器将被 FDL 取代。

标签: javascript php google-maps firebase-dynamic-links google-url-shortener


【解决方案1】:

问题是:您是否在 2018 年 5 月 30 日之前访问过网址缩短服务?如果不是(这是我的情况),我会收到 403 Forbidden 错误。所以这可能也是你的问题,as explained here

无论如何,您应该考虑使用 FDL(Firebase 动态链接)迁移(或创建)您的代码。

documentation 解释了如何使用 FDL 服务。创建项目后,您可以参考thisthis 来正确构建您的查询。

最后,您应该能够通过 Javascript 完成所有操作(不需要 PHP),并且您的代码应该看起来像这样(精简到最少的代码):

function initialize() {

  var reviewUrl = 'http://search.google.com/local/writereview?placeid=';

  var myLatLng = new google.maps.LatLng(46.2, 6.17);
  var mapOptions = {
    zoom: 4,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

  var input = document.getElementById('pac-input');

  var autocomplete = new google.maps.places.Autocomplete(input);

  autocomplete.addListener('place_changed', function() {

    var place = autocomplete.getPlace();

    if (!place.geometry) {
      return;
    }

    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }

    getShortLink(reviewUrl + place.place_id);
  });
}

function getShortLink(longUrl) {

  var apiKey = 'MY_API_KEY'; // Replace this with the appropriate value
  var params = {
    "longDynamicLink": "https://example.page.link/?link=" + longUrl + "&apn=com.example.android&ibi=com.example.ios", // Replace this with the appropriate values
    "suffix": {
      "option": "SHORT"
    }
  }

  $.ajax({
    url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=' + apiKey,
    type: 'POST',
    data: jQuery.param(params),
    contentType: "application/json",
    success: function(response) {
      alert(response.status);
    },
    error: function() {
      alert("error");
    }
  });
}

initialize();

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    由于 Google 停止了对 URL 缩短器的支持,另一种选择是使用 Firebase 动态链接 (FDL)。我对 FDL 进行了研究,发现它有点复杂,而且对于我想要实现的目标付出了太多的努力。

    我使用 Bitly Link 缩短 API 来缩短我的网址,具有与 Google 网址缩短器相同的功能且更易于实现。

    用它来缩短我的网址:

    function makeShort() {
                //Bitly Shortner Function using AJAX    
    
                 $.ajax({
                     //Type of XML query request
                    type: 'GET',
                    url: 'https://api-ssl.bitly.com/v3/shorten?access_token='+"ACCESS-TOKEN"+'&longUrl='+longUrl,
                    dataType: 'json',
                    success: function(result) {
    
                        //If Http status Code is "OK" 
                         if(result.status_code === 200) {
                                //Store the result in shorted_url variable
                                $('#shorted_url').html('<a href="url"> url </a>'.replace (/url/g ,result.data.url ))
                        } else {
                        //Do nothing
                        } 
                    },
                    //Otherwise return the error 
                    error: function(jqXHR, textStatus, errorThrown) {
    
                    }
                }); 
            }
    

    感谢您对此主题的回复。

    干杯。

    【讨论】:

      猜你喜欢
      • 2018-07-19
      • 2016-04-02
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      相关资源
      最近更新 更多