Javascript Google放置API和URL缩短器API

Javascript Google放置API和URL缩短器API,javascript,php,google-maps,firebase-dynamic-links,google-url-shortener,Javascript,Php,Google Maps,Firebase Dynamic Links,Google Url Shortener,简介:我正在尝试使用google places API和URL shortener API创建一个web应用程序。如果用户搜索一个地点,它会提取地点id并创建一个长URL-“+place_id”,然后使用此长URL使用Google URL shortener API将其缩短,然后将其填充到文本字段中,以便用户可以复制生成的短URL。我无法理解为什么它不会缩短URL。请注意,我有(API_键)在我的实际代码中。任何与此相关的帮助都将非常感谢 谢谢 Index.html代码 <input id

简介:我正在尝试使用google places API和URL shortener API创建一个web应用程序。如果用户搜索一个地点,它会提取地点id并创建一个长URL-“+place_id”,然后使用此长URL使用Google URL shortener API将其缩短,然后将其填充到文本字段中,以便用户可以复制生成的短URL。我无法理解为什么它不会缩短URL。请注意,我有(API_键)在我的实际代码中。任何与此相关的帮助都将非常感谢

谢谢

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>


地点ID



//此示例使用PlaceAutoComplete小部件允许用户进行搜索 //用于并选择一个位置。然后,示例将显示一个信息窗口,其中包含 //用户拥有的地点ID和有关该地点的其他信息 //选中。 //此示例需要位置库。包括库=位置 //第一次加载API时的参数。例如: // jQuery(“#gp_链接”)。单击(函数(){ jQuery(this.select(); }); 函数get\u short\u链接(place\u id){ jQuery.ajax({ 类型:“POST”, url:“curl.php”, 数据:“长URL=http://search.google.com/local/writereview?placeid=“+地点编号, 完成:功能(数据){ 警报(数据); jQuery(“#gp_link”).val(数据); } }); } 函数initMap(){ var map=new google.maps.map(document.getElementById('map'){ 中心:{lat:-33.8688,lng:151.2195}, 缩放:13 }); var input=document.getElementById('pac-input'); var autocomplete=new google.maps.places.autocomplete(输入); autocomplete.bindTo('bounds',map); map.controls[google.maps.ControlPosition.TOP_LEFT].push(输入); var infowindow=new google.maps.infowindow(); var infowindowContent=document.getElementById('infowindow-content'); setContent(infowindowContent); var marker=new google.maps.marker({ 地图:地图 }); marker.addListener('click',function()){ 信息窗口。打开(地图、标记); }); autocomplete.addListener('place\u changed',function(){ infowindow.close(); var place=autocomplete.getPlace(); 如果(!place.geometry){ 回来 } if(place.geometry.viewport){ map.fitBounds(place.geometry.viewport); }否则{ 地图。设置中心(地点。几何。位置); map.setZoom(17); } //使用位置ID和位置设置标记的位置。 标记。设定地点({ 地点id:place.place\u id, 位置:place.geometry.location }); marker.setVisible(true); infowindowContent.children['place-name'].textContent=place.name; infowindowContent.children['place-id'].textContent=place.place\u id; infowindowContent.children['place-address'].textContent= place.u地址; 信息窗口。打开(地图、标记); 获取短链接(place.place\u id); }); }
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
?>

问题是:您是否在2018年5月30日之前访问了URL缩短器服务?如果没有(这是我的情况),我会收到一个
403禁止
错误。因此,这可能也是您的问题

在任何情况下,您都应该考虑使用FDL(Firebase动态链接)迁移(或创建)代码

说明如何使用FDL服务。创建项目后,可以参考并正确生成查询

最后,您应该能够通过Javascript(无需PHP)完成所有操作,并且您的代码应该如下所示(精简到最少的代码):


希望这能有所帮助!

既然谷歌停止了对URL缩短器的支持,另一种选择是使用Firebase动态链接(FDL)。我研究了FDL,发现它有点复杂,而且对于我想要实现的目标来说太费劲了

我使用Bitly链接缩短器API来缩短我的URL,具有与Google URL缩短器相同的功能,并且更易于实现

用于缩短我的URL:

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) {

                }
            }); 
        }
函数makeShort(){
//使用AJAX的Bitly Shortner函数
$.ajax({
//XML查询请求的类型
键入:“GET”,
网址:'https://api-ssl.bitly.com/v3/shorten?access_token=“+”访问令牌“+”&longUrl=“+longUrl,
数据类型:“json”,
成功:功能(结果){
//如果Http状态代码为“OK”
if(result.status_code==200){
//将结果存储在url变量中
$('#shorted_url').html('.replace(/url/g,result.data.url))
}否则{
//无所事事
} 
},
//否则返回错误
错误:函数(jqXHR、textStatus、errorshown){
}
}); 
}
感谢您对此帖子的回复

干杯。

只是一个问题……您必须通过PHP查询URL缩写吗?可能值得一读,因为URL缩写将被FDL取代。
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) {

                }
            }); 
        }