I'm having an issue where the geocode isn't being executed. In my html file I have the following form below that takes in the address information.
<div class="row">
<div class="col s6">
<form id="addAddress" name="address_info" method="post">
<div class="row">
<div class="input-field col s12">
<input id="address" name="address" type="text" required>
<label for="address">Address</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="city" name="city" type="text" required>
<label for="city">City</label>
</div>
<div class="input-field col s2">
<input id="state" name="state" type="text" required>
<label for="state">State</label>
</div>
<div class="input-field col s4">
<input id="zipcode" name="zipcode" type="text" required>
<label for="zipcode">Zipcode</label>
</div>
</div>
<button class="btn light-blue darken-5" type="submit" name="address_info">Submit</button>
</form>
</div>
</div>
The js file then uses the information from the form to get the latitude and longitude values. The problem I'm getting is that the geocode function doesn't execute. The console logs show the fulladdress and 'before start geo', but nothing else.
function addAddress() {
document.getElementById("addAddress").addEventListener("submit", function() {
var geocoder = new google.maps.Geocoder();
const address = document.getElementById("addAddress").elements.namedItem("address").value;
const city = document.getElementById("addAddress").elements.namedItem("city").value;
const state = document.getElementById("addAddress").elements.namedItem("state").value;
const zipcode = document.getElementById("addAddress").elements.namedItem("zipcode").value;
var fulladdress = address + ' ' + city + ' ' + state + ' ' + zipcode;
console.log(fulladdress);
console.log("before start geo");
geocoder.geocode({'address': fulladdress}, function(results,status){
console.log("start geo");
if(status == google.maps.GeocoderStatus.OK){
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log(latitude, longitude);
console.log("after geo");
}
});
});
}
function main() {
addAddress();
}
document.addEventListener("DOMContentLoaded", main());
I have the js file and the google maps api with my api key linked to my html file. I have the Geocode API enabled. Any help will be appreciated thanks!
Edit:
function geolocate(address, callback){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status){
if(status == google.maps.GeocoderStatus.OK){
callback(results[0].geometry.location.lat(), results[0].geometry.location.lng());
}
});
}
function addAddress() {
document.getElementById("addAddress").addEventListener("submit", function() {
var geocoder = new google.maps.Geocoder();
const address = document.getElementById("addAddress").elements.namedItem("address").value;
const city = document.getElementById("addAddress").elements.namedItem("city").value;
const state = document.getElementById("addAddress").elements.namedItem("state").value;
const zipcode = document.getElementById("addAddress").elements.namedItem("zipcode").value;
var fulladdress = address + ' ' + city + ' ' + state + ' ' + zipcode;
console.log(fulladdress);
console.log("before start geo");
geolocate(fulladdress, function(latitude, longitude){
console.log(latitude, longitude);
});
});
}
Related
i am using ajax to post data from asp (as front) to Django rest api (as backend)
First, I had a problem in Accessing to different domain but it solved using CORS
then i had another error which is related to CSRF
and the error like above :Forbidden (CSRF cookie not set.)
i've used #csrf_exempt to pass this validation but i want a solution for use it without csrf exmption
i tried more than one solution but it's not working or maybe i dont understand the way
Is there any clearly solution to solve it in ajax
In Error 403 ,
'''
JQuery sends " xhr.send( options.hasContent && options.data || null );
'''
i'll include code of my .cshtml file bellow
'''
form id="std_form" class="mx-auto form-horizontal" method="POST" asp-antiforgery="false">
#Html.AntiForgeryToken()
<div class="box-body">
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="first">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="second">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="third">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer d-flex">
<button type="submit" id="save_btn" class="btn-success btn">Save</button>
</div>
<!-- /.box-footer -->
</form>
</div>
'''
'''
window.CSRF_TOKEN = "{% csrf_token %}";
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
'''
and this is ajax request
'''
$(document).on('submit', '#std_form', function (e) {
e.preventDefault();
let val1 = parseInt($('#first').val());
let val2 = parseInt($('#second').val());
let val3 = parseInt($('#third').val());
let x={val1,val2,val3};
$.ajax({
type: 'POST',
url: ('http://127.0.0.1:8000/Callfun/processdata/'),
data:{
First: val1,
Second:val2,
Third:val3,
csrfmiddlewaretoken: window.CSRF_TOKEN,
},
success: function (context) {
alert("Wooooooooowwwww");
$('#first').val(context.Max);
$('#second').val(context.Min);
$('#third').val(context.Avg);
},
error: function (context) {
alert("So Bad");
}
})
})
'''
I can't get value from input field in html.
This is my html:
<div class="form-group">
<label class="control-label col-sm-2" for="subject">Subject:</label>
<div class="col-sm-10">
<input class="form-control" id="idsubject" ng-model="subject" placeholder="Enter Subject">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="body">Body:</label>
<div class="col-sm-10">
<input class="form-control" id="idbody" ng-model="body" placeholder="Enter Body">
</div>
</div>
Then this is my controller insert:
// insert data
$scope.InsertData = function() {
var insert = {
subject: $scope.subject,
body: $scope.body
}
var promiseGet = GetAllEntryService.InsertData(insert);
GetAllEntry();
ClearModels();
promiseGet.then(function(pl) {
$scope.InsertData = pl.data
},
function(errorPl) {
console.log('Some Error in Getting Records.', errorPl);
});
}
But this return value post like http://localhost:51458/ServiceRequest.svc/InsertData?subject=undefined&body=undefined
I don't know why from input field not get the value.
This is my service insert:
this.InsertData = function (ticket, request, category, subCategory, subject, body, assignto, status, fileName, fileContent, fileBinary, isActive, createdBy, aCNo) {
return $http.post("http://localhost:51458/ServiceRequest.svc/InsertData?"&subject=" + subject + "&body=" + body);
};
this the picture output from inspect element developer network
Please help me what I'm missing in my code
I can see a couple of problems, first you are setting InsertData as a function and later you set it to data.
Then you have your service which takes separate params but you've pass an object to it:
this.InsertData = function (ticket, request, category, subCategory, subject, body, ...)
And your usage:
var insert = {
subject: $scope.subject,
body: $scope.body
}
var promiseGet = GetAllEntryService.InsertData(insert);
While you should've used it like this:
var promiseGet = GetAllEntryService.InsertData(/*ticket goes here*/, ... , $scope.subject, $scope.body, ...);
The below image is of the site I created with the fields that get sent to Firebase.
This is how its structured in Firebase, which is as expected
I would like to incorporate the drop boxes so they post above the ID, at the minute in my services.js I have the following:
var ref = new Firebase('leaguesdev.firebaseio.com/League');
But I would like the structure be somthing like
leaguesdev.firebaseio.com/League/dropdown1/dropdown2/Club
I'm not sure how much or how little you need to see but I will attempt to cover what I think you will want to see
services.js
'use strict';
angular.module('myApp.interviews')
.factory('interviewsService', ['$firebase','$firebaseArray','$q', function($firebase, $firebaseArray, $q) {
var ref = new Firebase('leagesdev.firebaseio.com/League');
var getData = function(callback){
return $firebaseArray(ref);
};
var showFalse = function(){
return false;
};
var showTrue = function(){
return true;
};
index.html
<div class="container" ng-controller="LoginCtrl" ng-show="authData">
<div class="row" ng-controller="InterviewsCtrl">
<div class="col-md-5" ng-show="addFormShow">
<h3> Add Clubs to Firebase</h3>
<form name="mainForm" ng-submit="addInterview()" novalidate style="border-color: transparent;">
<div class="form-group">
<label>Division</label>
<select class="form-control" placeholder="Division" ng-model="divisionname" id="dividionname">
<option value="" disabled selected>Please Select Division</option>
<option>Premier Division</option>
<option>Division 1</option>
<option>Division 2</option>
<option>Division 3</option>
<option>Division 4</option>
</select></div>
<div class="form-group">
<label>Club Name</label>
<input type="text" class="form-control" placeholder="Clubname" ng-model="clubname" id="clubname">
</div>
I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle
My goal is to have several input fields with Autocomplete functionality and each input will generate a marker on the map. I then need the map to zoom in to contain all of the markers. I have this working partially, without the Autocomplete functionality. I have tried adding the Google Maps API Places Autocomplete code to my for loop, but to no avail. It gives autocomplete functionality to all the input fields but only places a marker for the last input.
Any help/insight/guidance is appreciated.
Here is my code, the autocomplete is currently deleted since I couldn't get it to work.
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 well">
<div id="locations">
<form>
<label>Location 0</label>
<input id="address0" type="text" size="50" >
<button id="clearField0">Clear</button>
<div class="panel">
<label>Location 1</label>
<input id="address1" type="text" size="50">
<button id="clearField0">Clear</button>
</div>
<div class="panel">
<label>Location 2</label>
<input id="address2" type="text" size="50">
<button id="clearField0">Clear</button>
</div>
</form>
</div>
<button id="addField">+</button>
<button id="deleteField">-</button>
<button id="submit">Submit form</button>
</div>
<div class="span8">
<div id="map-wrapper">
<div id="google-map"></div>
</div>
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCtNo_o0u8wYeqgiFF-KpvAtEy18T-PvAo&sensor=false&callback=createMap"></script>
<script type="text/javascript">
var inputFields = parseInt($('form input').size());
var markers = [];
var createMap = function() {
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var myOptions = {
center : new google.maps.LatLng(35.9081, -78.8628), //center to RTP
zoom : 12,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById("google-map"), myOptions);
$("#submit").on("click", function() {
setAllMap(null);
markers.pop();
for (i=0; i<inputFields; i++) {
var location = $("#address" + i).val();
geocoder.geocode( {'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
latlngbounds.extend(results[0].geometry.location);
map.fitBounds(latlngbounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
};
});
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
$('#addField').click(function(){ //add input field to bottom of form
$('form').append('<div class="panel"><label>Location '+ inputFields +'</label><input id="address'+ inputFields +'" type="text" size="50"><button id="clearField'+ inputFields +'">Clear</button></div>');
inputFields++;
});
$('#deleteField').click(function(){ //delete last input field
$('.panel').last().remove();
inputFields--;
});
};
</script>
My first problem was including the places library in the API reference. Following that, I simply needed two lines of code from Google's Places Autocomplete example page, as opposed to the entire script they offer:
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
These two lines in my for loop solved the problem. Thanks again to Dr. Molle whose comment made me rethink what code I needed.