I am trying to use Google Places API, MAPS API and Distance Matrix API in my website for below purpose:
- Places API for displaying the places on the go, when user try to enter his address
- Distance Matrix to get distance between two locations
But as of now I am failing on first step only, where the drop down suggestions are not coming on my page. I followed the steps mentioned on " https://www.wix.com/corvid/forum/tips-tutorials-examples/how-to-use-google-maps-services-in-wix-code " and wix code examples mentioned at “https://code-examples.wix.com/google-places” and "https://editor.wix.com/html/editor/web/renderer/new?siteId=133728ba-356b-46ab-94b8-e966ec9c2537&metaSiteId=172fe8fa-89b0-4c9d-91b1-331c5df52952 ".
Below is my code snippet for backend API file:
import {fetch} from 'wix-fetch';
const key = "Google APIKEY";
// returns a list of place "suggestions" based on the user input
const apart1 = "https://maps.googleapis.com/maps/api/place/autocomplete/json?";
const apart2 = "&types=(cities)&key=";
export function autocomplete(string) {
let input = "input=" + string;
let url = apart1 + input + apart2 + key;
return fetch (url, {method: 'get'}).then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
});
}
// uses the unique place_id to retrieve details for the place
const dpart1 = "https://maps.googleapis.com/maps/api/place/details/json?";
const dpart2 = "&key=";
export function details(id) {
let placeid = "placeid=" + id;
let url = dpart1 + placeid + dpart2 + key;
return fetch (url, {method: 'get'}).then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
});
}
// returns locations name(s) based on the location's coordinates
const rpart1 = "https://maps.googleapis.com/maps/api/geocode/json?";
const rpart2 = "&key=";
export function reverse(lat, lng) {
let latlng = "latlng=" + lat + "," + lng;
let url = rpart1 + latlng + rpart2 + key;
return fetch (url, {method: 'get'}).then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
});
}
Followed by below code on my page:
// Written by Yisrael Hersch yisraelh@wix.com
import wixWindow from 'wix-window';
import {local} from 'wix-storage';
import {autocomplete} from 'backend/gmapsapi';
import {details} from 'backend/gmapsapi';
import {reverse} from 'backend/gmapsapi';
$w.onReady(function () {
// handle each suggestion repeater item
$w("#repeater1").onItemReady( ($w, itemData, index) => {
const text1 = $w("#text1");
text1.text = itemData.text1;
const text2 = $w("#text2");
text2.text = itemData.text2;
});
$w("#repeater1").collapse(); // hidden on page load
// handle each location detail line
$w("#repeater2").onItemReady( ($w, itemData, index) => {
const text3 = $w("#text3");
text3.text = itemData.text3;
const text4 = $w("#text4");
text4.text = itemData.text4;
});
$w("#repeater2").hide(); // hidden on page load
// retrieve saved location (if exists) from local storage
let id = local.getItem("place_id");
if(id === undefined || id === null || id.length === 0) {
// if no location saved, find the IP-based geographic location
geoloc();
}
else {
// if a location was saved in local storage, get the details
set_details(id);
}
});
function randomFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
let debounceTimer;
export function input1_keyPress_1(event, $w1) {
//export function input1_change(event, $w1) {
$w("#repeater2").data = [];
$w("#repeater2").hide();
if (debounceTimer) {
clearTimeout(debounceTimer); // ignore error
debounceTimer = undefined;
}
debounceTimer = setTimeout(() => { // ignore error
// use the current value to get a list of location suggestions
// we call the autocomplete() web module from the backend
let val = event.target.value;
if(val.length === 0)
return;
autocomplete(val).then(function (resp) {
// create an array of suggestions for the repeater
let predictions = resp.predictions;
let suggestions = [];
predictions.forEach(function (prediction) {
let item = { "_id": prediction.id, "text1": prediction.description, "text2": prediction.place_id };
suggestions.push(item);
});
$w("#repeater1").data = []; // clear the repeater contents
$w("#repeater1").data = suggestions; // add the suggestions to the repeater
$w("#repeater1").expand(); // we have data so we can expand the repeater
});
}, 150);
}
// this function is triggered when clicking on a suggestion list repeater item
export function container_click(event, $w) {
let place_id = $w("#text2").text;
set_details(place_id);
$w("#repeater1").collapse();
}
function set_details(val) {
//$w(“#spinner”).show();
details(val).then(function(resp) {
// find the city (locality) and country of our location
let place = resp.result;
var filtered_array = place.address_components.filter(function(address_component){
return address_component.types.includes("country");
});
var country = filtered_array.length ? filtered_array[0].long_name: "";
filtered_array = place.address_components.filter(function(address_component){
return address_component.types.includes("locality");
});
var locality = filtered_array.length ? filtered_array[0].long_name: "";
let name = place.formatted_address;
let id = place.place_id;
let utc = place.utc_offset;
let lat = place.geometry.location.lat;
let lng = place.geometry.location.lng;
local.setItem("place_city", name);
local.setItem("place_lat", lat);
local.setItem("place_lng", lng);
local.setItem("place_utc", utc);
local.setItem("place_id", id);
$w("#input1").value = name;
let detailsList =
[
{
"_id": "1",
"text3": "place name",
"text4": name
},
{
"_id": "2",
"text3": "latitude",
"text4": "" + lat
},
{
"_id": "3",
"text3": "longitude",
"text4": "" + lng
},
{
"_id": "4",
"text3": "utc",
"text4": "" + utc
},
{
"_id": "5",
"text3": "place id",
"text4": id
}
];
$w("#repeater2").data = []; // clear our repeater
$w("#repeater2").data = detailsList; // add data to our repeater
$w("#repeater2").show();
//$w(“#spinner”).hide();
});
}
//export function button1_click(event, $w) {
// $w("#repeater1").collapse();
// $w("#repeater2").data = [];
// $w("#repeater2").hide();
// geoloc();
//}
export function geoloc() {
//$w(“#spinner”).show();
wixWindow.getCurrentGeolocation()
.then( (obj) => {
let lat = obj.coords.latitude;
let lng = obj.coords.longitude;
reverse(lat, lng).then(function(resp) {
let status = resp.status;
if(status === "ZERO_RESULTS") {
let name = "Pittsburgh, PA, USA";
local.setItem("place_city", name);
local.setItem("place_lat", "40.44062479999999");
local.setItem("place_lng", "-79.9958864");
local.setItem("place_utc", "-240");
local.setItem("place_id", "ChIJA4UGSG_xNIgRNBuiWqEV-Y0");
$w("#input1").value = name;
return;
}
let results = resp.results;
var country = null, city = null, place_id = null;
var c, lc, component;
for (var r = 0, rl = results.length; r < rl; r += 1) {
let result = results[r];
// look for city (locality) and country
if (!city && result.types[0] === 'locality') {
for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
component = result.address_components[c];
if (component.types[0] === 'locality') {
city = component.long_name;
continue;
}
if (component.types[0] === 'country') {
country = component.long_name;
if(city && country)
break;
}
}
}
else {
continue;
}
if (city && country) {
place_id = result.place_id;
set_details(place_id);
break;
}
}
//$w(“#spinner”).hide();
});
} )
.catch( (error) => {
let errorMsg = error;
console.log(errorMsg);
});
}
with due respect, I have not removed “// Written by Yisrael Hersch yisraelh@wix.com” to give due credits to my Yisrale in my webssite code :).
Please help me correct my code.