How can I change input field for autocomplete (Google Maps API)?
autocomplete = new google.maps.places.Autocomplete(inputField, options);
function func1() {
// switch element inputField to inputField2 (how?)
}
Try this:
<script
src="https://maps.googleapis.com/maps/api/js?libraries=places">
</script>
<input type="text" id="loc1">
<input type="text" id="loc2">
<input type="text" id="loc3">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function initialize(){
var autocomplete1 = new google.maps.places.Autocomplete($("#loc1")[0], {});
var autocomplete2 = new google.maps.places.Autocomplete($("#loc2")[0], {});
var autocomplete3 = new google.maps.places.Autocomplete($("#loc3")[0], {});
google.maps.event.addListener(autocomplete1, 'place_changed', function () {
var place = autocomplete1.getPlace();
console.log(place.address_components);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I think this would be helpful : autofill. Create a autocomplete variable each with inputbox and create a single listener or multiple listener.
I hope this helps
Related
I need help with google places autocomplete API. I am getting the autocomplete address and lat and long from the API. Without restriction to a country the code works fine and I get the desired address, lat and long. However when I try to add country restriction, the lat and long fails to send along with my form.
Here is the working code without country restriction:
JS
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here is the code with country restriction that I need help with:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<script>
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('searchTextField')),
{types: ['geocode'],
componentRestrictions: {country: 'us'}});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the lines that's causing the problem:
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('searchTextField')),
{types: ['geocode'],
componentRestrictions: {country: 'us'}});
My form:
<html>
<head>
<title>Address Demo</title>
</head>
<body>
<form action="address.php" method="GET">
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading" style="background-color:#00CDCD">
<h2 class="panel-title">Address</h2>
</div>
<div class="panel-body">
<input name="address" id="searchTextField" placeholder="Enter area name" type="text" class="form-control" required>
<input type="hidden" name="latii" id="latitude">
<input type="hidden" name="lngii" id="longitude">
<input type="submit" name="submit" value="SUBMIT" class="bookingbtn top-10 bottom-20">
</div>
</div>
</form>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</body>
</html>
address.php
<?php
$address = $_GET['address'];
$latii = $_GET['latii'];
$lngii = $_GET['lngii'];
echo "$address </br>";
echo "$latii </br>";
echo "$lngii";
?>
Thanks for your help in advance.
I finally got it to work. Thanks to the answer here How to limit google autocomplete results to City and Country only.
My working code is:
<script>
function initialize() {
var options = {
types: ['geocode'],
componentRestrictions: {country: "us"}
};
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I am using vue js and I am able to pass username. But I am not able to pass lat and lng values. When checking, I am able to post username but lat and lng is coming as null.
My html code is
<form id="submitBox" method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
<div id="map"></div>
<input name="lat" type="text" id="lat" v-model="lat"><br>
<input name="lng" type="text" id="lng" v-model="lng">
<input name="username" type="text" class="form-control" id="name" placeholder="Name" required="required" v-model="username" data-parsley-minlength="4"/>
</form>
When Clicking on the map. I am able to load lat and lng values but I am not abe to pass
My script to load map values is
<script>
//map.js
//Set up some of our variables.
var map; //Will contain map object.
var marker = false; ////Has the user plotted their location marker?
//Function called to initialize / create the map.
//This is called when the page has loaded.
function initMap() {
//The center location of our map.
var centerOfMap = new google.maps.LatLng(52.357971, -6.516758);
//Map options.
var options = {
center: centerOfMap, //Set center.
zoom: 7 //The zoom value.
};
//Create the map object.
map = new google.maps.Map(document.getElementById('map'), options);
//Listen for any clicks on the map.
google.maps.event.addListener(map, 'click', function(event) {
//Get the location that the user clicked.
var clickedLocation = event.latLng;
//If the marker hasn't been added.
if(marker === false){
//Create the marker.
marker = new google.maps.Marker({
position: clickedLocation,
map: map,
draggable: true //make it draggable
});
//Listen for drag events!
google.maps.event.addListener(marker, 'dragend', function(event){
markerLocation();
});
} else{
//Marker has already been added, so just change its location.
marker.setPosition(clickedLocation);
}
//Get the marker's location.
markerLocation();
});
}
//This function will get the marker's current location and then add the lat/long
//values to our textfields so that we can save the location.
function markerLocation(){
//Get location.
var currentLocation = marker.getPosition();
//Add lat and lng values to a field that we can save.
document.getElementById('lat').value = currentLocation.lat(); //latitude
document.getElementById('lng').value = currentLocation.lng(); //longitude
}
//Load the map when the page has finished loading.
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
My vue js code is
<script>
submitBox = new Vue({
el: "#submitBox",
data: {
lat : '',
lng : '',
username: '',
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['lat'] = this.lat;
data['lng'] = this.lng;
data['username'] = this.username;
$.ajax({
url: 'http://127.0.0.1:8000/api/add/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert("Success")
}
else {
vm.response = e;
alert("Failed")
}
}
});
return false;
}
},
});
</script>
I am able to get username. But I am gettting null values for lat and lng.
BUT WHEN I CLICK ON THE MAP I AM ABLE TO PRINT LAT AND LNG values but I am not able to pass the same. Can anybody please help me to solve the issue.
v-model isn't recognizing that the value attribute of your "lat" input field has been programmatically changed. Instead, you can do something like this:
<input name="lat" type="text" id="lat" ref="myLatField" v-model="lat">
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['lat'] = this.$refs.myLatField.value;
...
Im not able to get place autocomplete so what should i do?
<input class="form-control" name="loc[]" onkeypress="return initialize(input);" required>
js code:
function initialize(input) {
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
You don't need to add onkeypress event, Autocomplete will handle that for you. Just pass your input element and some options to the Autocomplete constructor.
Example:
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'us'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=places"></script>
<input id="searchTextField" type="text" size="50" placeholder="Cities in US">
-- Update --
Using dynamically created input elements.
var form = document.getElementsByTagName('form')[0];
var options=[{placeholder:"Cities in US",options:{types:["(cities)"],componentRestrictions:{country:"us"}}},{placeholder:"Cities in FR",options:{types:["(cities)"],componentRestrictions:{country:"fr"}}}];
function addAutocomplete (elem, options) {
autocomplete = new google.maps.places.Autocomplete(elem, options);
}
function crateAutoCompleteInputs ( count, optoins ) {
for (var i = 0; i < count; i++) {
var input = document.createElement('input');
input.type = 'text';
input.placeholder = optoins[i].placeholder;
form.appendChild(input);
addAutocomplete(input, options[i].options)
}
}
crateAutoCompleteInputs(2, options)
input {
margin-right: 12px;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=places"></script>
<form></form>
I have got the current location with complete address and shown this in a <span> by ID. But i want to show this address in input type text also. My current code is
<script type="text/javascript">
var positionlatitude;
var positionlongitude;
var address;
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(document.getElementById('location_#item.Name'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
address = place.formatted_address;
positionlatitude = place.geometry.location.lat();
positionlongitude = place.geometry.location.lng();
});
});
navigator.geolocation.getCurrentPosition(success);
function success(position) {
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function (location) {
$('span[id^="address"]').html(location.results[0].formatted_address);
})
}
</script>
<label for="location">Your Location: </label><br />
<span id="address" class="input-form" ></span>
<input type="text" value="" name="address" id="geolocation"/>
Thanks To everyone If you consider this question.
now i got the answer.
document.getElementById("geolocation").value = location.results[0].formatted_address;
<input type="hidden" value="" name="address" id="geolocation"/>
This will set the address in input type hidden
I need to copy the text entered in a field (whether it was typed in, pasted or from browser auto-filler) and paste it in another field either at the same time or as soon as the user changes to another field.
If the user deletes the text in field_1, it should also get automatically deleted in field_2.
I've tried this but it doesn't work:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
var box1 = document.getElementById('field_1');
var box2 = document.getElementById('field_2');
box2.value = box1.value;
}
});
</script>
Any ideas?
You are almost there... The function is correct, you just have to assign it to the change event of the input:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
//Since you have JQuery, why aren't you using it?
var box1 = $('#field_1');
var box2 = $('#field_2');
box2.val(box1.val());
}
$('#field_1').on('change', onchange);
});
$(document).ready(function() {
$('.textBox1').on('change', function() {
$('.textBox2').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="textBox1"/>
<input type="text" class="textBox2"/>
If you are using jQuery, it is very easy - you need just register the right function on the right event :)
Here's the code:
<input id="foo" />
<input id="bar" />
$(function(){
var $foo = $('#foo');
var $bar = $('#bar');
function onChange() {
$bar.val($foo.val());
};
$('#foo')
.change(onChange)
.keyup(onChange);
});
JSFiddle: http://jsfiddle.net/6khr8e2b/
Call onchange() method on the first element onblur
<input type="text" id="field_1" onblur="onchange()"/>
try with keyup event
<input type="text" id="box_1"/>
<input type="text" id="box_2"/>
$('#box_1').keyup(function(){
$('#box_2').val($(this).val());
})
Try something like:
$(document).ready(function () {
$('#field_1').on('change', function (e) {
$('#field_2').val($('#field_1').val());
});
});
Heres a fiddle: http://jsfiddle.net/otwk92gp/
You need to bind the first input to an event. Something like this would work:
$(document).ready(function(){
$("#a").change(function(){
var a = $("#a").val();
$("#b").val(a);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="a" />
<input type="text" id="b" />
If you want that the value of the second field is updated as the same time that the first one, you could handle this with a timeout.
Each time a key is pressed, it will execute the checkValue function on the next stack of the execution. So the value of the field1 in the DOM will already be updated when this function is called.
var $field1 = $("#field_1");
var $field2 = $("#field_2");
$field1.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $field2.val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$field2.val(v1);
v2 = v1;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="field_1" value=""/><br/>
<input id="field_2" value=""/>