So I created AFC fields for street address, city, state, and zip and then I am using Google Maps to take the information in those fields and then populate two other ACF fields with the lat and long for that address. The issue I am having is that when I put in the address fields and click the publish/update button it does not grab the lat/long right away. When I click it a second time is when the grabs the lat/long and populates those ACF fields. This only occurs when I add a new address. If I use an address that has already been used on another post and reuse that same one for a new post it does grab the lat/long on first try. So based off of that I assume that the first click is grabbing the lat/long and the second click is being used to populate the lat/long fields.
But what I need to accomplish is that both of those steps(grabbing lat/long and populating lat/long fields) to happen on the same publish/update button click. Below is the code I currently am using:
add_action( 'post_submitbox_start', 'qd_fake_publish_button' );
function qd_fake_publish_button()
{
$screen = get_current_screen();
if( ($screen->parent_base == 'edit') && ( $screen->id == 'opportunity' ))
{
print '<button id="acquireLatLong" class="button button-primary button-large">Publish</button>';
}
}
add_action( 'admin_print_footer_scripts', 'project_pins_save_post', 11);
function project_pins_save_post() {
$screen = get_current_screen();
if( ($screen->parent_base == 'edit') && ( $screen->id == 'opportunity' ))
{
$script = '
<script type="text/javascript" src="MY_GOOGLE_API_KEY"></script>
<script type="text/javascript">
function AcquireLatLont() {
var mygc = new google.maps.Geocoder();
var qd_street = document.getElementById("acf-field_5abe83dfda81b").value;
var qd_city = document.getElementById("acf-field_5abe4bea43cc3").value;
var qd_state = document.getElementById("acf-field_5abe4bf543cc4").value;
var qd_zip = document.getElementById("acf-field_5abe4bfb43cc5").value;
var address = qd_street + ", " + qd_city + ", " + qd_state + " " + qd_zip;
mygc.geocode({ "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("acf-field_5abe845fda81c").value = results[0].geometry.location.lat();
document.getElementById("acf-field_5abe846ada81d").value = results[0].geometry.location.lng();
document.getElementById("publish").click();
} else {
alert("Geocoder failed due to: " + status);
}
});
return false;
}
</script>
<script type="text/javascript" >
jQuery( document ).ready(function( $ ) {
$("#acquireLatLong")[0].textContent = $("#publish")[0].value;
$("#acquireLatLong").click(function() {
AcquireLatLont();
});
});
</script>
';
echo $script;
}
}
Haven't really worked with populating ACF fields dynamically before, so not sure where this code snippet is messing up.
Related
I am new to jQuery and PHP. This might be a trivial question or not.
Normally jQuery handles form input, post it to PHP, and then let PHP passes it to a database.
In my case, I have the current user's geographic location and I compare the user's geographic location against the destination's geographic location in JavaScript. If those two locations are close which means the user is arrived at the destination, record in the database by inserting the destination's Identifier (let's just say Id =1 to keep it simple) for the current user under the Place_Id filed in database. The table in the database only has two columns (userId and placeId).
I wonder how to achieve by jQuery and PHP.
Here is the JavaScript code for geographic locations comparison.
I need help on the function postIt() to initiate PHP using jQuery and the associate PHP.
<script type="text/javascript" ,
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
var lat;
var long;
window.onload=function(){
getLocation();
}
function getLocation() {
if (navigator.geolocation) {
watchId = navigator.geolocation.watchPosition(showPosition, locationError,
{maximumAge:0, timeout:10000, enableHighAccuracy:true});
}
else {
alert("Browser doesn't support Geolocation. Visit http://caniuse.com to
discover browser support for the Geolocation API.");
}
}
function locationError(error) {} // error function here
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
lat = position.coords.latitude;
long = position.coords.longitude;
comparePosition();
}
function comparePosition()
{
var userCurrentLat = lat;
var userCurrentLong = long;
var Dest1_Lat = 38.00; //this is just for demo
var Dest1_Long = -72.00; //this is just for demo
if (userCurrentLat == Dest1_Lat
&& userCurrentLong == Dest1_Long)//just a simplified way of comparison
{
postIt();
}}
function postIt()
{ $.post ('insertDest1.php', {current_user_id, //pseudo jQuery code here
destinationId(1)}, callback function() ) //where I need help
}
</script>
PHP (insertDest1.php)
<?php
include ('mysqli_connect.php');
$query = "INSERT INTO user (userId,placeId) VALUES
('current_user_id' , '1')";
$result = #mysqli_query ($dbc, $query); // Run the query.
if ($result) { // If it ran OK.
// Print a message.
echo '<h1 id="mainhead">Success!</h1>';
}
else { // If it did not run OK.
echo '<h1 id="mainhead">Error</h1>';
}
?>
Use $.ajax for more configuration options:
function postIt()
{
$.ajax({
url: 'insertDest1.php',
type: 'POST',
data:{
userId: 'current_user_id', // replace with actual user id
placeId: 'the_place_id' // replace with actual place id
},
success: function(serverResponse) {
// handle output from server here ('Success!' or 'Error' from PHP script)
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// handle any network/server errors here
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
Setup PHP file to handle POST data from AJAX
<?php
include ('mysqli_connect.php');
# Always sanitize input from $_POST variable to prevent SQL injection
$userId = $dbc->escape_string($_POST['userId']); // current_user_id
$placeId = $dbc->escape_string($_POST['placeId']); // the_place_id
$query = "INSERT INTO user (userId, placeId) VALUES ('".$userId."' , '".$placeId."')";
$result = #mysqli_query ($dbc, $query); // Run the query.
if ($result) { // If it ran OK.
// Print a message.
echo '<h1 id="mainhead">Success!</h1>';
}
else { // If it did not run OK.
// Print error.
echo '<h1 id="mainhead">Error</h1>';
}
?>
This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 8 years ago.
I am working on a hybrid app using the Appgyver Steroids framework and I'm trying to implement a 'detect user location' feature whereby the user can toggle a switch to choose whether they'd like their location (long & lat) to be detected automatically, or alternatively they can enter their location (city, postcode or county) into a text box and the longitude and latitude will be calculated on click of a button based on their input/selection.
When the user toggles the switch into the 'on' position and taps submit, the navigator.geolocation.getCurrentPosition is fired and calls the relevant functions which then stores their current longitude and latitude in localStorage. This works perfectly.
However, when the user toggles the switch into the 'off' position, my geocode function [manuallyGeoCode()] which codes their location into long and lat doesn't seem to fire in time and so the alert is fired straight after calling that geocode function before it has had time to actually set the localStorage value. I've researched using a callback and I've looked into using the jQuery deferred method, both of which I've had no success with using. Any help would be massively appreciated! Thanks for reading.
Here's my code:
<h3>Your location</h3>
<ul class="list">
<li class="item item-toggle">Use my current location
<label class="toggle toggle-balanced">
<input type="checkbox" id="myLocationToggle" checked="true">
<div class="track">
<div class="handle"></div>
</div>
</label>
</li>
<li class="item item-input">
<input type="text" id="userLocation" placeholder="City, town or postcode" disabled="true">
</li>
</ul>
<button class="button button-balanced" id="getLongLat">Get long/lat</button>
$(function(){
AutoGeoCode();
});
function AutoGeoCode(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
}
$('#getLongLat').on('click',function(){
localStorage.latToPost = '';
localStorage.lngToPost = '';
if(localStorage.userLatAutoDetected != '0' || localStorage.userLngAutoDetected != '0'){
localStorage.latToPost = localStorage.userLatAutoDetected;
localStorage.lngToPost = localStorage.userLngAutoDetected;
}
else{
manuallyGeoCode(); // this doesn't finish in time so it jumps to the alert below and shows empty values.
}
alert('geodata is: {'+localStorage.latToPost+'}, {'+localStorage.lngToPost+'}');
});
$('#myLocationToggle').on('click',function(){
if($(this).is(':checked')){
$('#userLocation').val('').prop('disabled',true);
AutoGeoCode();
}
else{
$('#userLocation').val('').prop('disabled',false);
localStorage.userLatAutoDetected = '0';
localStorage.userLngAutoDetected = '0';
}
});
function onSuccess(position){
localStorage.userLatAutoDetected = position.coords.latitude;
localStorage.userLngAutoDetected = position.coords.longitude;
}
function onError(error){
alert('current location could not be auto detected. Error: ' + error);
}
//Autocomplete location search box
function initialize() {
var address = (document.getElementById('userLocation'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
}); //end google.maps.event
}
function manuallyGeoCode(){
var address = $('#userLocation').val();
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
localStorage.latToPost = results[0].geometry.location.lat();
localStorage.lngToPost = results[0].geometry.location.lng();
}
else {
alert('Your location could not be geocoded.');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Please find the difference in the handle and the manual geocode functions
$('#getLongLat').on('click',function(){
localStorage.latToPost = '';
localStorage.lngToPost = '';
if(localStorage.userLatAutoDetected != '0' || localStorage.userLngAutoDetected != '0'){
localStorage.latToPost = localStorage.userLatAutoDetected;
localStorage.lngToPost = localStorage.userLngAutoDetected;
alert('geodata is: {'+localStorage.latToPost+'}, {'+localStorage.lngToPost+'}');
}else{
manuallyGeoCode(function(){
alert('geodata is: {'+localStorage.latToPost+'},{'+localStorage.lngToPost+'}');
}); // this doesn't finish in time so it jumps to the alert below and shows empty values.
}
});
function manuallyGeoCode(cb){
var address = $('#userLocation').val();
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
localStorage.latToPost = results[0].geometry.location.lat();
localStorage.lngToPost = results[0].geometry.location.lng();
cb();
}
else {
alert('Your location could not be geocoded.');
}
});
}
I need to get latitude and longitude by city name using bing map. Here is my code.
function Geocode() {
//Create Bing Maps REST Services request to geocode the address provided by the user
var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
+ "Colombo"
+ "?output=json"
//Set the callback function
+ "&jsonp=GetLocationCoordinates"
+ "&key=Ai5r7K1Jy95BfrDbOV9PPvoBqYicNNe3Bapi7PczGda-l30CjbpHeLnK8XQmYcKl";
//Submit the request
MakeServiceRequest(geocodeRequest);
}
function MakeServiceRequest(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
GetLocationCoordinates();
}
function GetLocationCoordinates(geocodeResponse) {
if(geocodeResponse==null) document.getElementById("txt").innerText = "This is null";
if (geocodeResponse &&
geocodeResponse.resourceSets &&
geocodeResponse.resourceSets.length > 0 &&
geocodeResponse.resourceSets[0].resources &&
geocodeResponse.resourceSets[0].resources.length > 0) {
setLoc(geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[0], geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[1], 10);
}
else {//The location could not be geocoded
var md = new Windows.UI.Popups.MessageDialog("The location could not be geocoded");
md.showAsync();
}
}
But in here it never called function GetLocationCoordinates(geocodeResponse). How can I make to call it.?
Probably because you are running this from the local context. Create an iframe and add the code in that resulting html file.
I've wrapped the code in a namespace. This way you can define where the function will be called rather than sticking your functions in the global namespace. Note I commented out your direct call of the function, its not needed.
Create a /pages/map/map.html, map.js, map.css (in other words, create a /pages/map and right click on it and select add new item and choose 'page' type named map)
In map.js include the following after 'use strict', or include in another javascript file. It's up to you.
WinJS.Namespace.define("LocationServices", {
GetLocationCoordinates: function (geocodeResponse) {
if (geocodeResponse == null) document.getElementById("txt").innerText = "This is null";
if (geocodeResponse &&
geocodeResponse.resourceSets &&
geocodeResponse.resourceSets.length > 0 &&
geocodeResponse.resourceSets[0].resources &&
geocodeResponse.resourceSets[0].resources.length > 0) {
setLoc(geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[0], geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[1], 10);
}
else {//The location could not be geocoded
var md = new Windows.UI.Popups.MessageDialog("The location could not be geocoded");
md.showAsync();
}
},
Geocode: function () {
//Create Bing Maps REST Services request to geocode the address provided by the user
var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
+ "Colombo"
+ "?output=json"
//Set the callback function
+ "&jsonp=LocationServices.GetLocationCoordinates"
+ "&key=Ai5r7K1Jy95BfrDbOV9PPvoBqYicNNe3Bapi7PczGda-l30CjbpHeLnK8XQmYcKl";
//Submit the request
this.MakeServiceRequest(geocodeRequest);
},
MakeServiceRequest: function (request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
// GetLocationCoordinates();
}
});
In turn load map.html (which includes a reference to map.js and has your input id='txt')
<iframe src="ms-appx-web:///pages/map/map.html"></iframe>
I am using google API to detect client location however it always shows to me "Your Location Was Not Detected By Google Loader".
I need to find country code of the client location however it is not working for me.
<script src="http://www.google.com/jsapi" language="javascript"></script>
<script language="javascript">
if (google.loader.ClientLocation != null) {
document.write("Your Location Is: " + google.loader.ClientLocation.address.country_code);
} else {
document.write("Your Location Was Not Detected By Google Loader");
}
</script>
ClientLocation object returns null when Google cannot geolocate your IP address. This could happen because of many reasons, one being the API cannot resolve your IP address.
Maybe you can try other solutions such as
http://html5demos.com/geo
or ask your server to do this.
Try this:
<script type="text/javascript">
if(google.loader.ClientLocation) {
var latitude = google.loader.ClientLocation.latitude;
var longtitude = google.loader.ClientLocation.longitude;
var city = google.loader.ClientLocation.address.city;
var region = google.loader.ClientLocation.address.region;
var country = google.loader.ClientLocation.address.country;
var countrycode = google.loader.ClientLocation.address.country_code;
} else {
// ClientLocation not found or not populated
// so perform error handling
}
</script>
Change
if (google.loader.ClientLocation != null) {
to
if (google.loader.ClientLocation){
Hope, this helps.
I have a Javascript form where a user inputs an address, city, and state. When this form is submitted, I want the address to be converted into latitude and longitude, and to store those two values to a database. Any help at all is greatly appreciated!
Check this out:
http://batchgeo.com/lookup/
You can use the Google Maps API v3, example:
//get the input from user, in a normal looking address string
var add = this.ListingAddress + ', ' + this.ListingCity + ', ' + this.ListingZipCode;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': add }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var LatLong = results[0].geometry.location; //here is the LatLong
} else {
alert("Address not found! Error Code: " + status);
}
});