Place.formatted_address in google maps api is undefined - google-maps-autocomplete

I'm trying to get the value of place.formatted_address, but I don't understand why it's undefined everytime I try to console log the value. I'm using this project for the autocomplete function in google maps
const google = window.google;
const options = {
componentRestrictions: { country: "mo" },
fields: ["address_components", "geometry", "icon", "name"],
strictBounds: false,
types: ["establishment"],
};
const autocomplete = new google.maps.places.Autocomplete(this.$refs["origin"], options);
google.maps.event.addListener(autocomplete, "place_changed", () => {
const place = autocomplete.getPlace();
console.log(place.formatted_address)
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
console.log(lat,lng)
})
},

Related

Parameters can not be read from an Ajax get request in my controller

I am trying to send a longitude and latitude from my view to my controller. However it is not being picked up in my controller.
Here is the view
fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${query}.json?access_token=pk.eyJ1Ijoiam9ubnlwZWluIiwiYSI6ImNrN2c3aDFjZjA4OG4zZW8yZ3ozcjF4bWQifQ.8PT8uVs7CsaJU5PNDLZdHw`)
.then(response => response.json())
.then((data) => {
const lon = data.features[0].geometry.coordinates[0];
const lat = data.features[0].geometry.coordinates[1];
displayMap(lat, lon);
$.ajax({
url: "/set_location",
data: {"lon": lon, "lat": lat},
type: "GET",
success: function (data) {
console.log(data);
}
});
});
};
// Event Trigger
submit.addEventListener("submit", (event) => {
event.preventDefault();
const input = document.querySelector('.form-control');
fetchMap(input.value);
});
submit.addEventListener("submit", (event) => {
event.preventDefault();
const input = document.querySelector('.form-control');
fetchMap(input.value);
});
The controller is below
def set_location
Client.last.lat = params[:lat]
Client.last.lon = params[:lon]
{ 'lat': params[:lat], 'lon': params[:lon] }
end
Any help would be greatly appreciated !!

How to view a single entry with oModel.read in UI5 Application

I want to display a single entry with oModel.read in my UI5 application and store it in a variable.
What i want to do is, to select a single entry of my Model and store it in a variable:
If i execute my code i get the following in the Browser-Console:
https://ibb.co/FmPNSPm
Here is my code (but is not working):
var hostPort = "";
var oDataPath = "/.../KOMMI_SERVICE/";
var sServiceUrl= hostPort + oDataPath;
var oModel = new sap.ui.model.odata.ODataModel (sServiceUrl, true);
var oJsonModel = new sap.ui.model.json.JSONModel();
var text123;
oModel.read("/Komm(ZSMATERIALTEXT ='"+text123+")",oEntry,null,false,
function(oData, oResponse){
},function(err){
console.log("err");
});
I think that this path "/Komm(ZSMATERIALTEXT ='"+text123+")" is not correct.
You can try using filter. For example:
var sPath = "/Komm";
var oFilter = [
new Filter("ZSMATERIALTEXT", "EQ", text123)
];
oModel.read(sPath, {
filters: oFilter,
success: function (oData, oResponse) {
// save variable
},
error: function (oError) {
// show error
}
});
Try this:
I think you're missing a " ' "...
oModel.read("/Komm(ZSMATERIALTEXT ='"+text123+"')",oEntry,null,false,
function(oData, oResponse){
},function(err){
console.log("err");
});
Or
oModel.read("/Komm", {
filters: [
new sap.ui.model.Filter("ZSMATERIALTEXT", sap.ui.model.FilterOperator.EQ, text123)
],
success: function (oData, oResponse) {
// do some...
},
error: function (oError) {
// error
}
});

Difficulty with upload csv to knockout js table (ASP MVC)

I've been working with these two tutorials, but am having difficulty merging them together to get an upload csv to populate the table. It most likely is my lack of understanding of the view model.
Here's the tutorial for the knockout js editable table from the knockout js site: KnockoutJS: Editable Grid Table
And here's the tutorial for uploading a csv I'm referencing:
KnockoutJS - Upload CSV
Here's the javascript code I've been working on to upload a csv to my table. I keep getting "JavaScript runtime error: Unable to get property 'push' of undefined or null reference" - I marked in comments the problem spot. As you can see, I'm having trouble with the view model.
<script>
var UserModel = function (users) {
var self = this;
self.users = ko.observableArray(users);
self.addUser = function () {
self.users.push({
id: "",
firstName: "",
lastName: ""
});
};
self.removeUser = function (user) {
self.users.remove(user);
};
self.save = function (form) {
sendData = ko.toJSON(self.users);
$.ajax({
url: '/Users/CreateMultiple',
contentType: 'application/json',
async: true,
type: 'POST',
dataType: 'json',
data: sendData,
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS");
}
});
};
};
var viewModel = new UserModel([
{ id: "", firstName: "", lastName: "" }
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });
/////
/////Upload CSV
/////
$('#lnkUpload').click(function () {
var FileToRead = document.getElementById('UserFile');
if (FileToRead.files.length > 0) {
var reader = new FileReader();
reader.onload = Load_CSVData;
reader.readAsText(FileToRead.files.item(0));
}
});
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
UserModel.users.push(new UserModel()//here's my problem
.id(csvID)
.firstName(csvFirstName)
.lastName(csvLastName)
)
});
}
</script>
I was able to identify the fully qualified for the observable array which in turn made it work:
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
viewModel.users.push({
id: csvID,
firstName: csvFirstName,
lastName: csvLastName
});
}

How to get exact place details by using lat,lng of only one place using Google place API?

I want place details especially address using the only lat,lng coordinate using Google place APIs.
I tried nearbysearch, text search and radar search, but it requires radius also. Then I tried to geocode API but it is giving details of more than one place, and I want exactly one place details.
So is there any way to achieve this?
install twitter gem: gem 'twitter'
Create Controller:
class Api::MapController < ApplicationController
def new
end
def show
client = Twitter::REST::Client.new do |config|
config.consumer_key = "your_consumer_key"
config.consumer_secret = "your_consumer_secret"
config.access_token = "your_access_token"
config.access_token_secret = "your_access_token_secret"
end
#center: {lat: -34.397, lng: 150.644},
latitude = params[:lat]
longitude = params[:lng]
#str = '31.515181,74.345034,10km'
str = "#{latitude.to_s},#{longitude.to_s},10km"
#search_results = client.search( '', geocode: str ).take(15)
render json: #search_results
end
end
you can set 0kM if 1 result is required. and pass query for specific result in client.search( 'Coffe Shops', geocode: str ).take(15) method
Finally add this Javascript add and show markers on google map
computed_latitude = 150.644;
computed_longitude = -34.397;
map = null;
function initMap() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
computed_latitude = pos.lat;
computed_longitude = pos.lng;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: computed_latitude, lng: computed_longitude},
zoom: 6
});
// fetch tweets
console.log('Fetching tweets now...');
$.ajax({
url: "http://localhost:3000/api/map/show", // Route to the Script Controller method
type: "GET",
dataType: "json",
data: {lat: computed_latitude, lng: computed_longitude}, // This goes to Controller in params hash, i.e. params[:file_name]
complete: function () {
},
success: function (data, textStatus, xhr) {
console.log('Got the tweets... Drawing marker.');
var marker = [];
for (var i = 0; i < data.length; i++) {
if (!($.isEmptyObject(data[i].geo))) {
var computed_latitude = data[i].geo.coordinates[0];
var computed_longitude = data[i].geo.coordinates[1];
myLatlng = {lat: computed_latitude, lng: computed_longitude};
marker[i] = new google.maps.Marker({
position: myLatlng,
map: map,
title: data[i].text
});
var id = data[i].id_str;
var name = data[i].user.screen_name;
function some_function(name, id) {
window.location = 'https://twitter.com/'+ name + '/status/' + id ;
};
marker[i].addListener("click", function(){
some_function(name, id);
}, false);
}
}
},
error: function () {
alert("Ajax error!")
}
});
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
What it does in my case:
It get user location then send Long, Lat to api/map_controller.rb then using Twitter Gem. it searched nearby public tweets within radius of 10km. with no query string. the controller respond in JSON format to javascript based google map. then it appends tweets to map.

Backbone.js - How to save model by form and post to server

I'm n00b in BackboneJS/RequireJS and I'm developing an web app that use a RESTful API.
So I've a model like this:
models/pet.js
define([
'backbone'
], function(Backbone){
var PetModel = Backbone.Model.extend({
urlRoot: 'http://localhost:3000/pet',
idAttribute: '_id',
defaults: {
petId: "",
type: "",
name: "",
picture: "",
description: "",
breed: "",
size: "",
sex: "",
age: "",
adopted: false,
}
});
return PetModel;
});
a collection: collections/pets.js
define([
'backbone',
'models/pet'
], function(Backbone, PetModel){
var PetsCollection = Backbone.Collection.extend({
url: 'http://localhost:3000/pets',
model: PetModel,
});
return PetsCollection;
});
And a view that renders a form to add new models (Maybe it's possible another way more elegant)
views/petAddNew.js
define([
'jquery',
'backbone',
'models/pet',
'collections/pets',
'text!templates/pet/addNew.html'
], function($, Backbone, PetModel, PetsCollection, petAddNewTemplate){
var PetAddNewView = Backbone.View.extend({
el: $('#formAdd'),
template: _.template(petAddNewTemplate),
events: {
'click #add' : 'submitAdd',
},
initialize: function() {
this.model = new PetModel();
this.collection = new PetsCollection();
_.bindAll(this, 'submitAdd');
},
render: function() {
var view = this;
view.$el.html( view.template );
return view;
},
submitAdd: function(e) {
//Save Animal model to server data
e.preventDefault();
var pet_data = JSON.stringify( this.getFormData( this.$el.find('form') ) );
this.model.save(pet_data);
this.collection.add(this.model);
return false
},
//Auxiliar function
getFormData: function(form) {
var unindexed_array = form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
},
});
return PetAddNewView;
});
So when I submit the form I don't post any data to server. I don't know how to fix it.
Any ideas? Thanks in advance!
You need set the attributes first and then save.
//Auxiliar function
getFormData: function(form) {
var self = this;
var unindexed_array = form.serializeArray();
$.map(unindexed_array, function(n, i){
self.model.set({
n['name']: n['value']
});
});
}
Now this.model.save() works (saving on the server side).
You can see it work in a fiddle.
Model.save expect an object/hash of new values, just like Model.set. Here you're passing a string as the attributes arguments.

Resources