Get the place_id of a city using google places autocomplete - google-places-api

I'm using an input field with google places autocomplete. I' ve set autocomplete to predict only cities but I'm stuggling to find a simple way to get the unique place_id of the selected city. I don't want to use it with google maps. I need it just to identify with a unique value the selected city.. Thanks in advance..
Here's my JS:
<script src="maps.googleapis.com/maps/api/js?libraries=places"; type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var options = { types: ['(cities)'] };
var input = document.getElementById('searchCity');
var autocomplete = new google.maps.places.Autocomplete(input,options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And here's my PHP:
<form method="GET" action=<?php echo $_SERVER['PHP_SELF'];?>>
<input id="searchCity" type="text" size="50"
placeholder="Enter a City" autocomplete="on" name="city">
<br>
<?php if (!empty($_GET['city']) ) {
echo $_GET['city'];
} else {
echo "not set";
}
unset($_GET['city']); ?>
</form>
<!-- Here I would like to show the place_id of the selected city-->
</div>

You don't need PHP to display the place details. You just need a Javascript event handler for place_changed.
E.g. add this code to your initialize function:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var form = input.parentElement;
form.appendChild(document.createTextNode("Place ID is " + place.place_id));
});
These samples from Google's docs contain complete examples of using the place_changed event. They're worth looking at:
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete
https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder

Related

How to add google reCAPTCHA in the newsletter form in magento?

How to add google reCAPTCHA with the newsletter in magento to stop receiving newsletter emails in the spam.
Add the below code in the "form file" under the form tag to resolve your query.
<div class="recaptcha" style="overflow:hidden;position:relative;">
<input type="checkbox" id="recaptcha-verification-1" name="recaptcha-verification-1" value="" class="hide required-entry" style="visibility:hidden;position:absolute;left:-1000000px" />
<div id="recaptcha-1"></div>
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('recaptcha-1', {
'sitekey': "6Lf9tBcTAAAAAEbCd2XlhPGH3o850Qp9ZMJJ2fr2",
'theme': "light",
'callback': function(response) {
if (response.length > 0) {
$('recaptcha-verification-1').writeAttribute('value', 'checked');
$('recaptcha-verification-1').checked = true;
}
}
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=en" async defer></script></div>
I was facing the same issue and I made it solved one extension "Google Invisible reCaptcha"
Wait... I changed few modifications in JS code also.
After installing extension set Site key and secret in admin side and open subscription.phtml
YOUR-PROJECT/app/design/frontend/YOURTHEME/default/template/newsletter/subscribe.phtml
Add code just after Form Tag.
<div class="g-recaptcha" data-sitekey="YOUR-SITE-KEY"></div>
In the last of file add this JS Snippet.
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#recaptcha_response_field').addClass('required-captcha-entry');
})
var yourFormValidationObj = new VarienForm('newsletter-validate-details');
Validation.add('required-captcha-entry', ' ', function(v) {
return !Validation.get('IsEmpty').test(v);
})
</script>
It worked for me. Cheers if it works for you..

google.maps.places.Autocomplete requests Location too many times in Firefox

in my website, I have a singn_up-form and use the Google-Api to give the user some suggestions. The API requests the location of the user once in Internet-Explorer. But if I try Firefox, the requests are looped until I click "Standort immer Freigeben" - it means "always accept".
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{ types: ['geocode'] });
}
The code is loaded at document.ready and contains more code, but this snippet also reproduces the error.
Does anyone has some ideas?
Try this :
put the apis in your <head></head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
put this in your body tag:
<label for="autocomplete">Please Insert an address:</label>
<br>
<input id="autocomplete" type="text" size="100">
put this in your onload function:
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
this is my code :
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="autocomplete">Please Insert an address:</label><br>
<input id="autocomplete" type="text" size="100">
</body>
</html>
You might have kept some onfocus attribute as given in Google Maps API Example
<input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
OR
If you don't require keeping bounds for places suggestions, you may want to remove it
OR
If you need to set bounds for suggestions keep some condition to not call location consent every time, if user gives permission.
Please keep your condition in geolocate() function
Issue is happening only in Mozilla FireFox
What you want to do is this:
function handlePermission() {
navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
geoBtn.style.display = 'none';
navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
} else if (result.state == 'denied') {
geoBtn.style.display = 'inline';
}
});
}
then put handlePermission(); after your callback function receives permission

Input Button as Input image will not work

On my website i have a button which when clicked takes you to one of two random youtube videos. However i would like to change this to a image in stead of a button.I have tried to change it to a INPUT type="image" but this doesn't work. Here is the code i am using.
<SCRIPT language="JavaScript">
<!--
function get_random()
{
var ranNum= Math.floor(Math.random()*2);
return ranNum;
}
function getaGame()
{
var whichGame=get_random();
var game=new Array(2)
game[0]= "https://www.youtube.com/watch?feature=player_detailpage&v=NcFQF3PZFRk#t=722s";
game[1]= "https://www.youtube.com/watch?v=klBAW4MQffU";
location.href = game[whichGame];
}
//-->
</SCRIPT>
<FORM name="form1">
<center>
<INPUT type="button" onClick="getaGame()" >
</center>
</FORM>
Thanks for any help
An onclick event can be fired from any element. Here are some examples!

Multiple AJAX Callbacks and Creating a List

I'm sure this is a common question but I have an input field and a button. Whenever the button is pressed an ajax call is performed returning a string. I understand that if you attach it to a div in the original file, that div will erase any strings or numbers in it and replace with the returned string. What would be the most efficient way to allow for every single callback to be displayed on the screen real time? I attempted it but it appears that dynamically changing the javascript variable that assigns which div tag the ajax callback inserts into does not work. Does anyone know either what is wrong with this code or a more efficient way to write this code, i.e. with php, etc.
<div id="part1">
<input type="text" id="text"/>
<input type="button" value="button" id="button"/>
</div>
<div id="hidden" class="2"></div>
<div id="part2"></div>
<div id="part3"></div>
<div id="part4"></div>
<div id="part5"></div>
<script type="text/javascript" >
$('#button').click(function () {
var text = $('#text').val();
$.post('ajaxskeleton.php', {
red: text
}, function(){
var number = $('#hidden').attr("class");
$('#part' + number).html(text);
var number = number+1;
var class_name = $('#hidden').attr('class')
$('#hidden').removeClass(class_name);
$('#hidden').addClass(number);
$('#text').val('');
});
});
</script>
Instead of erasing its contents with .html(), you could append the new results to an existing div . For example, suppose you want to append the results to a div with id results:
$('#button').click(function () {
var text = $('#text').val();
$.post('ajaxskeleton.php', { red: text }, function() {
$("<li>" + text + "</li>").appendTo($("#results"));
});
});​
Here's a DEMO.
I think something like the following would work.
<div id="container">
<input type="text" id="text"/>
<input type="button" value="button" id="button"/>
</div>
<ol id="responses"></ol>
$("#button").click(function() {
$.post('ajaxskeleton.php', {red:text}, function(data) {
$("#responses").append("<li>" + data + "</li>");
});
});
This just builds up an ordered list with the responses that come back from the Ajax calls, which I think is what your aiming to do.

ajax check if link is on website

I'm looking for a way to check if a link exists on a certain page. I know that this is possible with a ping, but I really don't know how to do this.
What I have is a list of links to other webpages, they should have a backlink to my page also. I want to check this, when the backlink is there, a text should appear, something like "ok" and when the result is negative, something like "no backlink"
I know the urls of the pages where my link should appear, in case you need to know that.
Any help would be great!
I have found a piece of code wich I think could be used to serve my needs. I self don't know how, but it would be great if anyone can help me with this.
This is the code:
<html>
<head>
<script language="javascript" type="text/javascript">
<!--
var ajax = new XMLHttpRequest();
function pingSite() {
ajax.onreadystatechange = stateChanged;
ajax.open('GET', document.getElementById('siteToCheck').value, true);
ajax.send(null);
}
function stateChanged() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
document.getElementById('statusLabel').innerHTML = "Success!";
}
else {
document.getElementById('statusLabel').innerHTML = "Failure!";
}
}
}
-->
</script>
</head>
<body>
Site To Check:<br />
<input type="text" id="siteToCheck" /><input type="button" onclick="javascript:pingSite()" />
<p>
<span id="statusLabel"></span>
</p>
</body>
You can't natively use Javascript to parse external domains, I used a proxy page which sniffs the content and feeds it to the ajax callback.
My solution basically grabs the source of the site to check and sees if a string, which can be your site link matches. I would assume this should be sufficient rather than trying to parse and look for anchors, but you can be as thorough as you want ( parse the whole thing as a DOM element and look for href attribute value ).
Let me know if you run into any issues.
<?php
$query = isset($_POST['submitted']) ? true : false;
if ( $query ) {
$url = #file_get_contents( $_POST['site-url'] );
if ( $url && strlen( $url ) > 0 ) {
$checkFor = $_POST['check-for'];
$match = preg_match( '/' . $checkFor . '/', $url );
echo $match ? 'string (link) is found' : 'string not found';
} else {
echo 'could not connect to site..';
}
exit;
}
?>
<form action="" id="site-checker">
<div class="field">
<label for="site-url">Site to check:</label>
<input id="site-url" name="site-url" value="http://jquery.com">
</div>
<div class="field">
<label for="check-for">Check for:</label>
<input id="check-for" name="check-for" value="docs.jquery.com">
</div>
<input type="hidden" name="submitted" value="true">
<input type="submit">
</form>
<div id="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$('#site-checker').submit(function(e) {
e.preventDefault();
$.ajax({
url:'check.php',
type:'POST',
data:$('#site-checker').serialize(),
success:function(html) {
$('#result').html( html );
}
});
});
</script>
IMHO it would be better to perform this task in a server side script. Depending on your platform there might be functions for sending HTTP requests and HTML parsing which is what you need here. Javascript has cross domain restrictions which will prevent you from sending ajax requests to different domains than the one that is hosting the web page.

Resources