Google places API and URL shortener API

2.4k views Asked by At

Intro: I am trying to create a web app using google places API and URL shortener API. If a user searches for a place it pulls the place-id and creates a long URL - "http://search.google.com/local/writereview?placeid=" + place_id" and then use this long URL to shorten it using Google URL shortener API and then populate it in the text field so the user can copy the generated short URL. I am not able to figure out why it won't shorten the URL. Please note I have (api_key) in my actual code. ANy help with be really appreciated.

Thanks.

Index.html code

<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 file

<?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
?>
2

There are 2 answers

0
Hamza Choudary On BEST ANSWER

Since Google is stopping it's support for URL shortener, another alternative was to use Firebase Dynamic Links (FDL). I researched on FDL and found it to be a bit complicated and too much effort for what I wanted to achieve.

I used Bitly Link shortener API for shortening my URL, have the same features as Google URL shortener and easier to implement.

Used this for shortening my 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) {

                }
            }); 
        }

Thanks for your replies on this thread.

Cheers.

0
MrUpsidown On

Question is: did you access the URL shortener service before May 30. 2018? If not (which is my case), I receive a 403 Forbidden error. So that might be the issue for you as well, as explained here.

In any case, you should probably look into migrating (or creating) your code with FDL (Firebase Dynamic Links).

The documentation explains how to use the FDL service. Once you have created your project, you can refer to this and this to build your query properly.

In the end, you should be able to do everything via Javascript (no PHP needed) and your code should look something like this (stripped to minimal code):

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();

Hope this helps!