Add custom output to woocommerce cart as a product - javascript

i made some code for google maps api that calculates the distance from one place to another, but i have a problem with adding the output to the woocommerce price (also displaying it as a product). this is the code i wrote:
The thought was.. that when i press submit, to have a product that would get values from the output of the distance and price, and then add it as a product.
` function add_fixed_text_product_to_cart( $cost ) {
global $woocommerce;
$product_id = 1825; //the ID of fixed text product
$product = wc_get_product( $product_id );
if ( $product ) {
$woocommerce->cart->add_to_cart( $product_id, 1, 0, array(), array( 'cost' => $cost ) );
}
}
add_action( 'wp_ajax_add_fixed_text_product_to_cart', 'add_fixed_text_product_to_cart' );
add_action( 'wp_ajax_nopriv_add_fixed_text_product_to_cart', 'add_fixed_text_product_to_cart' );
function add_custom_price_to_cart_item( $cart_object ) {
if ( is_admin() ) {
return;
}
foreach ( $cart_object->cart_contents as $key => $value ) {
if ( isset( $value['cost'] ) ) {
$value['data']->set_price( $value['cost'] );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price_to_cart_item', 10, 1 );
function zip_code_input_shortcode()
{
ob_start();
?>
<input id="address" type="text" placeholder="Enter address" style="text-align: center;">
<div id="address-dropdown"></div>
<div id="output">
<span id="distance_result"></span>
<br><br>
<span id="cost_result"></span>
<br><br>
<button id="submit_zipcode">Submit</button>
</div>
<script>
jQuery(document).ready(function() {
jQuery('#submit_zipcode').click(function() {
// Get the calculated cost
var cost = parseFloat(jQuery('#cost_result').text().split(' ')[1].replace(',', '.'));
// Add the information to the WooCommerce cart as a fixed text
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: {
'action': 'add_fixed_text_product_to_cart',
'cost': cost
},
success: function(data) {
console.log(data);
}
});
});
});
function initMap() {
var startingLocation = new google.maps.LatLng(55.84336022202228, 9.835100295423425);
var input = document.getElementById('address');
var options = {
types: ['address'],
componentRestrictions: { country: 'dk' }
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
var destination = place.formatted_address;
var destination_lat = place.geometry.location.lat();
var destination_lng = place.geometry.location.lng();
var postal_code = "";
// Get the postal code from the address components
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (addressType === "postal_code") {
postal_code = place.address_components[i].long_name;
}
}
// Check if the postal code is within the range of 1000 to 4999
if (postal_code >= 999 && postal_code <= 4999) {
alert("Vi montere desværre ikke varmepumper på Sjælland.");
return;
}
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [startingLocation],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status === 'OK') {
var distance_result = response.rows[0].elements[0].distance.text;
var distance_value = response.rows[0].elements[0].distance.value / 1000;
distance_value = distance_value.toFixed(2);
if (distance_value <= 25) {
var cost = 0;
} else {
var cost = (distance_value - 25) * 5.95;
cost = cost.toFixed(2);
}
document.getElementById('distance_result').innerHTML = 'Distance: ' + distance_result;
document.getElementById('cost_result').innerHTML = 'Cost: ' + cost.toString().replace('.', ',') + ' Danish kroner';
} else {
alert('Error: ' + status);
}
});
});
}
</script>`
(i dident include the API for this)
i tried to create some JS for this, but it dident work..
`jQuery(document).ready(function() {
jQuery('#submit_zipcode').click(function() {
// Get the calculated cost
var cost = parseFloat(jQuery('#cost_result').text().split(' ')[1].replace(',', '.'));
// Add the information to the WooCommerce cart as a fixed text
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: {
'action': 'add_fixed_text_product_to_cart',
'cost': cost
},
success: function(data) {
console.log(data);
}
});
});
});`

Related

set google origin search box address with a variable

I'm trying to make origin SearchBox destination be string with legit direction, but when I do so I still need to select the first option for it to work (to calculate distance).
Got the this searching around to calculate distance between 2 points and it works perfectly:
How can I add multiple searchBoxes in my google maps api web?
I got a string for example :albrook mall which i know exist( this string is dynamic is coming from a variable and all address are validated. get the needed address pass it to a variable so I can read it on the frontEnd, and set the value of search box in the html. the value is updated with jquery
But what happens is that I still have to click on the origin search box then this list all possible locations which in my case is the first one, how can I make the map either auto select the first option or recognize the address that is set in the input value?
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 9.0271554,
lng: 79.4816371
},
zoom: 15
});
var marker = new google.maps.Marker({
map: map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.avoidTolls = true;
this.avoidHighways= true;
//this.provideRouteAlternatives= true,
this.avoidFerries= true;
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode,
avoidTolls: this.avoidTolls
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
computeTotalDistance(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
time = (totalTime / 60).toFixed(2)
document.getElementById("totalkm").innerHTML ="" + totalDist + "km" ;
document.getElementById("totaltime").innerHTML ="" + time + " minutos";
if(totalDist <= 5){
document.getElementById("totalCost").innerHTML =" $3.50";
}
else{
kmPrice = (totalDist - 5) * 0.75;
document.getElementById("totalCost").innerHTML ="$" +(kmPrice + 3.50).toFixed(2)+ "";
}
}
function send_handle(){
let name=document.getElementById("name").value;
///let lastname= document.getElementById("lastname").value;
let inst= document.getElementById("instructions").value;
let origin= document.querySelector(".selectButtons input#orign").value;
let destination= document.querySelector(".selectButtons input#destn").value;
let cost= document.getElementById("totalCost").innerHTML;
let distance= document.getElementById("totalkm").innerHTML;
// win.focus();
}
</script>
<html>
<div class="selectButtons" >
<input type="text" id="orign" placeholder="origen">
<input type="text" id="destn" placeholder="destino">
<span> Distancia en KM <div id="totalkm">0km</div> </span>
<span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
<span> costo por envio<div id="totalCost">$0</div></div> </span>
</div>
</html>
You can call the places service to get the PlaceId (with your string), then pass that placeId into the constructor for your AutocompleteDirectionsHandler or if you already have the PlaceId (you are allowed to store those), just use it, although you probably want to initialize the origin input with the string.
var origin = "Allbrook, Panama";
var originInput = document.getElementById('orign');
originInput.value = origin;
const request = {
query: origin,
fields: ["name", "geometry", "place_id"],
};
var originPlaceId;
var service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
originPlaceId = results[0].place_id;
console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
new AutocompleteDirectionsHandler(map, originPlaceId);
map.setCenter(results[0].geometry.location);
}
});
Add the initial origin placeId to the AutocompleteDirectionsHandler constructor:
function AutocompleteDirectionsHandler(map, originPlaceId) {
this.map = map;
this.originPlaceId = originPlaceId;
// ...
on load:
after selecting destination from dropdown:
code snippet:
let map;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 9.0271554,
lng: 79.4816371
},
zoom: 15
});
var origin = "Allbrook, Panama";
var originInput = document.getElementById('orign');
originInput.value = origin;
const request = {
query: origin,
fields: ["name", "geometry", "place_id"],
};
var originPlaceId;
var service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
originPlaceId = results[0].place_id;
console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
new AutocompleteDirectionsHandler(map, originPlaceId);
map.setCenter(results[0].geometry.location);
}
});
var marker = new google.maps.Marker({
map: map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map, originPlaceId) {
this.map = map;
this.originPlaceId = originPlaceId;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.avoidTolls = true;
this.avoidHighways = true;
//this.provideRouteAlternatives= true,
this.avoidFerries = true;
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode,
avoidTolls: this.avoidTolls
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
computeTotalDistance(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
time = (totalTime / 60).toFixed(2)
document.getElementById("totalkm").innerHTML = "" + totalDist + "km";
document.getElementById("totaltime").innerHTML = "" + time + " minutos";
if (totalDist <= 5) {
document.getElementById("totalCost").innerHTML = " $3.50";
} else {
kmPrice = (totalDist - 5) * 0.75;
document.getElementById("totalCost").innerHTML = "$" + (kmPrice + 3.50).toFixed(2) + "";
}
}
function send_handle() {
let name = document.getElementById("name").value;
///let lastname= document.getElementById("lastname").value;
let inst = document.getElementById("instructions").value;
let origin = document.querySelector(".selectButtons input#orign").value;
let destination = document.querySelector(".selectButtons input#destn").value;
let cost = document.getElementById("totalCost").innerHTML;
let distance = document.getElementById("totalkm").innerHTML;
// win.focus();
}
function createMarker(place) {
if (!place.geometry || !place.geometry.location) return;
const marker = new google.maps.Marker({
map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name || "");
infowindow.open(map);
});
}
window.initMap = initMap;
#map-canvas {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<html>
<div class="selectButtons">
<input type="text" id="orign" placeholder="origen" />
<input type="text" id="destn" placeholder="destino" />
<span> Distancia en KM <div id="totalkm">0km</div> </span>
<span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
<span> costo por envio<div id="totalCost">$0</div> </span>
</div>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>
</html>

Phonegap Android is showing error E/Web Console﹕ Uncaught ReferenceError: google is not defined

I am facing a problem. My map is not loading on IOS but when I run it on android device it displays nothing and throws an error in log
E/Web Console﹕ Uncaught ReferenceError: google is not defined at line no 64
I am using a store locator API
Store Locator API
The maps works fine when i test it on ripple emulate and IOS device, But When it comes towards android it stuck.
My code is
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&callback=storeLocator" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
$.fn.storeLocator = function (options) {
var settings = $.extend({
'mapDiv': 'map',
'listDiv': 'list',
'formID': 'user-location',
'pinColor': 'fe7569',
'startPinColor': '66bd4a',
'pinTextColor': '000000',
'storeLimit': 10,
'distanceAlert': 60,
'xmlLocation': 'data/wholecar.xml',
'addressErrorMsg': 'Please enter valid WA address address or postcode',
'googleDistanceMatrixDestinationLimit': 50,
'defaultLat': 115.857469,
'defaultLng': -31.953004,
'defaultLocationName': 'Perth, WA'
}, options);
return this.each(function () {
var $this = $(this);
// global array of shop objects
var _locationset = new Array();
var geocoder;
// Calculate distances from passed in origin to all locations in the [_locationset] array
// using Google Maps Distance Matrix Service https://developers.google.com/maps/documentation/javascript/reference#DistanceMatrixService
var GeoCodeCalc = {};
GeoCodeCalc.CalcDistanceGoogle = function (origin, callback) {
var destCoordArr = new Array();
var subFunctionTokens = [];
$.each(_locationset, function (ix, loc) {
destCoordArr.push(loc.LatLng);
});
for (var i = 0; i < destCoordArr.length; i = i + settings.googleDistanceMatrixDestinationLimit) { // Google Distance Matrix allows up to 25 destinations to be passed in
var tempArr = destCoordArr.slice(i, Math.min(i + settings.googleDistanceMatrixDestinationLimit));
subFunctionTokens.push(this.CallGoogleDistanceMatrix(i, origin, tempArr));
}
$.when.apply($, subFunctionTokens)
.then(function () {
callback(true);
});
};
GeoCodeCalc.CallGoogleDistanceMatrix = function (startIndex, origin, destinations) {
var token = $.Deferred();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function (response, status) {
if (response && response.rows.length) {
var results = response.rows[0].elements;
$.each(results, function (j, val) {
if (results[j].status != "ZERO_RESULTS") {
_locationset[startIndex + j].Distance = GoogleMapDistanceTextToNumber(results[j].distance.text);
}
});
token.resolve();
}
});
return token.promise();
};
// Converts "123.45 mi" into 123.45
function GoogleMapDistanceTextToNumber(str) {
return Number(str.replace(/[^0-9.]/g, ""));
}
// removes Google Maps URL unfriendly chars from a string
function formatGoogleMapUrlString(str) {
return str.replace("&", "%26").replace(" ", "+");
}
//Geocode function for the origin location
geocoder = new google.maps.Geocoder();
function GoogleGeocode() {
this.geocode = function (address, callbackFunction) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = {};
result.latitude = results[0].geometry.location.lat();
result.longitude = results[0].geometry.location.lng();
result.formatted_address = results[0].formatted_address;
result.address_components = results[0].address_components;
callbackFunction(result);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
this.geocodeLatLng = function (LatLng, callbackFunction) {
geocoder.geocode({ 'location': LatLng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
callbackFunction(results[0]);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
}
//Process form input
$(function () {
$(document).on('submit', '#' + settings.formID, function (e) {
$("#lblError").html("");
//Stop the form submission
e.preventDefault();
//Get the user input and use it
var userinput = $('form').serialize();
userinput = userinput.replace("address=", "");
if (userinput == "") {
handleError(settings.addressErrorMsg);
}
var g = new GoogleGeocode();
var address = userinput;
g.geocode(address, function (data) {
if (data != null) {
showAddress(data);
mapping(data.latitude, data.longitude);
} else {
//Unable to geocode
handleError(settings.addressErrorMsg);
}
});
//Replace spaces in user input
userinput = formatGoogleMapUrlString(userinput);
});
});
$(document).ready(function () {
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
//map.setCenter(pos);
var g = new GoogleGeocode();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
g.geocodeLatLng(latlng, function (address) {
if (address) {
showAddress(address);
} else {
//Unable to geocode
handleNoGeolocation('Error: Unable to geocode address');
}
});
// do the mapping stuff
mapping(position.coords.latitude, position.coords.longitude);
}, function () {
handleNoGeolocation("Tracking of location was not allowed.");
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
});
function showAddress(address) {
$("#lblAddress").html(address.formatted_address);
// find a postcode and show it in the address textbox
$.each(address.address_components, function (i, val) {
if (val.types[0] == "postal_code") {
$("#address").val(val.short_name);
return false; // breaks the each() loop
}
});
}
function handleNoGeolocation(error) {
if (error) {
var content = error;
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
handleError(content + " Using default location.");
mapping(settings.defaultLat, settings.defaultLng);
$("#lblAddress").html(settings.defaultLocationName);
}
function handleError(error) {
$("#lblError").html(error);
}
//Now all the mapping stuff
function mapping(orig_lat, orig_lng) {
$(function () {
//Parse xml with jQuery
$.ajax({
type: "GET",
url: settings.xmlLocation,
dataType: "xml",
success: function (xml) {
_locationset = new Array();
$(xml).find('Placemark').each(function (i) {
var shop = {
Name: $(this).find('name').text(),
//Take the lat lng from the user, geocoded above
LatLng: new google.maps.LatLng(
$(this).find('coordinates').text().split(",")[1],
$(this).find('coordinates').text().split(",")[0]),
Description: $(this).find('description').text(),
Marker: null,
Distance: null
};
_locationset.push(shop);
});
// Calc Distances from user's location
GeoCodeCalc.CalcDistanceGoogle(new google.maps.LatLng(orig_lat, orig_lng), function (success) {
if (!success) { //something went wrong
handleError("Unable to calculate distances at this time");
}
else {
//Sort the multi-dimensional array numerically
_locationset.sort(function (a, b) {
return ((a.Distance < b.Distance) ? -1 : ((a.Distance > b.Distance) ? 1 : 0));
});
// take "N" closest shops
_locationset = _locationset.slice(0, settings.storeLimit);
//Check the closest marker
if (_locationset[0].Distance > settings.distanceAlert) {
handleError("Unfortunately, we currently don't have nearest location details for your area.");
}
//Create the map with jQuery
$(function () {
var orig_LatLng = new google.maps.LatLng(orig_lat, orig_lng);
//Google maps settings
var myOptions = {
center: orig_LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(settings.mapDiv), myOptions);
//Create one infowindow to fill later
var infowindow = new google.maps.InfoWindow();
//Add user location marker
var marker = createMarker(orig_LatLng, "0", settings.startPinColor);
marker.setAnimation(google.maps.Animation.DROP);
var bounds = new google.maps.LatLngBounds();
bounds.extend(orig_LatLng);
$("#" + settings.listDiv).empty();
$(_locationset).each(function (i, location) {
bounds.extend(location.LatLng);
letter = String.fromCharCode("A".charCodeAt(0) + i);
if (((location.Distance * 1.69)<=30)&&(location.Distance != null))
{
location.Marker = createMarker(location.LatLng, letter, settings.pinColor);
create_infowindow(location);
listClick(letter, location);
}
});
// zoom in/out to show all markers
map.fitBounds(bounds);
function listClick(letter, shop) {
$('<li />').html("<div class=\"list-details\"><div class=\"list-content\">"
+ "<div class=\"list-label\">" + letter + "<\/div>"
+ "<div class=\"loc-name\">" + shop.Name + "<\/div> <div class=\"loc-addr\">" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div class=\"loc-addr2\"><i>approx. " + Math.round(shop.Distance * 1.69) + " kilometers</i><\/div>" : "")
+ "<div class=\"loc-web\"><a href=\"http://maps.google.co.uk/maps?saddr="
+ formatGoogleMapUrlString($("#address").val()) + "+%40" + orig_lat + "," + orig_lng
+ "&daddr=" + formatGoogleMapUrlString(shop.Name) + "+%40" + shop.LatLng.lat() + "," + shop.LatLng.lng()
+ "&hl=en" + "\" target=\"_blank\">>Get directions</a><\/div><\/div><\/div>")
.click(function () {
create_infowindow(shop, "left");
}).appendTo("#" + settings.listDiv);
};
//Custom marker function - aplhabetical
function createMarker(point, letter, pinColor) {
//Set up pin icon with the Google Charts API for all of our markers
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor + "|" + settings.pinTextColor,
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
//Create the markers
return new google.maps.Marker({
position: point,
map: map,
icon: pinImage,
shadow: pinShadow,
draggable: false
});
};
//Infowindows
function create_infowindow(shop, listLocation) {
var formattedAddress = "<div class=\"infoWindow\"><b>" + shop.Name + "<\/b>"
+ "<div>" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div><i>" + Math.round(shop.Distance * 1.69) + " kilometers<\/i><\/div><\/div>" : "<\/div>");
//Opens the infowindow when list item is clicked
if (listLocation == "left") {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
}
//Opens the infowindow when the marker is clicked
else {
google.maps.event.addListener(shop.Marker, 'click', function () {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
})
}
};
});
}
});
}
});
});
}
});
};})(jQuery);
</script>
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
$('#map-container').storeLocator();
try{
var pageid = $(".MainContent").attr('id');
var title = $(".MainContent").attr('data-title');
//alert(title);
//alert("pageshow"+pageid);
if(title != undefined)
Analytic.sendScreenName(title);
}catch(e){
//alert(e);
}
}
</script>
<!DOCTYPE html>
<div class="address">
<label>
We have identified your location as:
</label>
<label id="lblAddress">
</label>.
<label>Or enter your location here.</label>
</div>
<form id="user-location" class="well form-search" method="post" action="#">
<div id="form-input">
<input type="text" id="address" name="address" value="" class="input-medium search-query" />
</div>
<div id="submit-btn">
<button type="submit" data-theme="b" name="submit" class="btn btn-warning" data-mini="true" value="submit-value">Submit</button></div>
<div class="error">
<label id="lblError"></label>
</div>
</form>
</div>
<div id="map-container">
<div id="loc-list">
<div id="loc-list-wrapper">
<ul id="list">
</ul>
</div>
</div>
<div id="map">
</div>
</div>
</div></div>
Try using this:
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
On Device Ready Load google DomListener.
Something like this - google.maps.event.addDomListener(window, 'load');
Also check you have added google maps script -
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false" ></script>
and you have allowed all intents in config file:
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

Search Form for Google Maps, using a multiselect dropdown

I have shop names, type, lng, lat, etc stored in the database.
Some of the shops are of more than one type, so the type field is like this:
Shoe & Footwear|*|Children & Baby Wear.
My search form works for searching everything except for using the Multiselect to narrow down the results.
How can I get it to narrow down the results, depending on which Multiselect options are selected.
I have removed some of the search fields:
<form id="advanced-search" class="advanced-search search-collapsed clearfix" method="POST">
<select id="advsearch-boutiquetype" size="5" multiple="multiple" name="bform[boutique-drop-advanced][]" title="Boutique Dropdown">
<option id="Bridal_Shops_Designers_box" value="Bridal_Shops_Designers">Bridal Shops & Designers</option>
<option id="Children_Baby_Wear_box" value="Children_Baby_Wear">Children & Baby Wear</option>
<option id="Ladies_Fashions_box" value="Ladies_Fashions">Ladies Fashions</option>
<option id="Lingerie_box" value="Lingerie">Lingerie</option>
<option id="Maternity_Wear_box" value="Maternity_Wear">Maternity Wear</option>
<option id="Men's_Wear_box" value="Men's_Wear">Men's Wear</option>
<option id="Shoe_Footwear_box" value="Shoe_Footwear">Shoe & Footwear</option>
</select>
<input id="advsearch-submit-button" class="submit" type="submit" value="search" onclick="update();">
</form>
The update() function:
function update() {
var km_miles = jQuery("#km_miles").val();
var distance = jQuery("#distance-input").val();
var street = jQuery("#advsearch-street").val();
var city = jQuery("#advsearch-city").val();
var county = jQuery("#countyLocationAdvanced").val();
var country = 'Ireland';
var type = jQuery("#advsearch-boutiquetype").val();
var search_address = street + ' ' + city + ' ' + county + ' ' + country;
if (km_miles === 'km') {
var cal_km_miles = '6371';
} else {
var cal_km_miles = '3959';
}
if(street || city || county){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': search_address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("countyLocation").value = county;
jQuery('#countyLocation').val(county);
getBoutiques(distance, results[0].geometry.location, cal_km_miles, type);
} else {
alert('Geocode error: ' + status);
}
});
}
}
The function getBoutiques():
function getBoutiques(dst, center, cal_dst, btypes){
// Read the data
if (typeof center != 'undefined') {
var centerlat = center.lat();
var centerlng = center.lng();
}
downloadUrl("index.php?option=com_boutiques_manager&view=boutiquesxml&county=" + document.getElementById("countyLocation").value.replace(/\s/g, '') + "&distance=" + dst + "&centerlat=" + centerlat + "&centerlng=" + centerlng + "&km_miles=" + cal_dst, function(doc) {
var xmlDoc = xmlParse(doc);
// Clear previous overlays
marker = null;
marker = new Array();
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
// create the marker
var marker = createMarker(point);
}
});
}
The downloadUrl() is returning this:
<markers>
<marker name="Test1" types="Ladies Fashions|*|Children & Baby Wear" profiletype="basic" city="Dublin 14" county="Co. Dublin" lat="53.29294764" lng="-6.229290545" count="" boutiqueimage="" link="boutique/page/1036/1"></marker>
<marker name="Test2" types="Ladies Fashions" profiletype="basic" city="Dublin 2" county="Co. Dublin" lat="53.342819" lng="-6.261962" count="" boutiqueimage="" link="boutique/page/1037/1"></marker>
<marker name="Test3" types="Men's Wear" profiletype="basic" city="Dublin 2" county="Co. Dublin" lat="53.345013" lng="-6.262699" count="" boutiqueimage="" link="boutique/page/1188/1"></marker>
</markers>
Database Query:
$county = str_replace('.', '. ', $_GET['county']);
$dst = (int) $_GET['distance'];
$km_miles = $_GET['km_miles'];
$btypes = $_GET['btypes'];
$mylat = $_GET['centerlat'];
$mylng = $_GET['centerlng'];
// Initialize variables.
$query = $db->getQuery(true);
$query->select(
'c.cb_profiletype, cp.user_id, cp.cbp_user_profile_id, cp.cbp_banned, cp.cbp_boutiquename, cp.cbp_city, '
. 'cp.cbp_countylist, cp.cbp_boutiquetypes, cp.cbp_maplng as lng, cp.cbp_maplat as lat, cp.cbp_boutiqueimage, pt.b_max, null AS total, '
. '( '.$km_miles.' * acos( cos( radians('.$mylat.') ) * cos( radians( cp.cbp_maplat ) ) * cos( radians( cp.cbp_maplng ) - radians('.$mylng.') ) + sin( radians('.$mylat.') ) * sin( radians( cp.cbp_maplat ) ) ) ) AS distance'
);
$query->from('#__comprofiler c');
$query->join('INNER', '#__comprofiler_profiles cp ON cp.user_id = c.id');
$query->join('INNER', '#__cb_profiletypes pt ON pt.alias = c.cb_profiletype');
$query->where('cp.cbp_boutiquetypes <> \'\' AND cp.cbp_maplng <> \'\' AND cp.cbp_maplat <> \'\' AND cp.cbp_countylist <> \'\' AND cp.cbp_banned = \'0\' AND cp.cbp_enableboutique = \'Yes\' AND cp.cbp_countylist = \''.$county.'\'');
$query->having('distance < \''.$dst.'\'');
$query->order('cp.cbp_boutiquename ASC');
$db->setQuery($query);
$tmpList = $db->loadObjectList();
// Set some values to make nested HTML rendering easier.
foreach ($tmpList as $item) {
if(trim($item->lat)!='' && trim($item->lng)!='' && $item->cbp_user_profile_id <= $item->b_max) {
$list[][$item->user_id] = $item;
}
}
The types are in cp.cbp_boutiquetypes

How to refresh only a div, not the complete page

I have this code that selects the type of a restaurant. After selecting any type the page is refreshed and after some SQL processing I get all restaurants corresponding to the selected type and show it in Google Maps.
How can I do that without refreshing the complete page, like only refreshing the <div> containing Google Maps?
<select class="mapleftS" name="type" id="type" onchange="changeType(this.value)">
<option value="0">كل الانواع</option>
<?$type = mysql_query("select * from rest_type ");
while($rod = mysql_fetch_array( $type )) {
if($rod[id] == $_REQUEST['type'])
$selll = 'selected';
else {$selll = '';
?>
<option value="<?=$rod[id]?>" <?=$selll?> ><?=$rod[name]?></option>
<? } ?>
</select>
<script>
function changeType( id ) {
parent.location = '?type=' + id;
}
$(function() {
var text_menu = $("#type option:selected").text();
$("#ddddd_").html(text_menu);
});
</script>
After selection this code is run:
if($_REQUEST['type']) {
// do some thing and refrsh map div
} else {
// do some thing and refrsh map div
}
And the following element contains Google Maps:
<div id="mppp" class="map"></div>
JS for Google Maps:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=SOMEAPIKEY&sensor=true"></script>
<script type="text/javascript">
var address_index = 0, map, infowindow, geocoder, bounds, mapinfo, intTimer;
$(function (){
mm();
});
mm = function() {
// Creating an object literal containing the properties you want to pass to the map
var options = {
zoom: 15,
center: new google.maps.LatLng(24.701564296830245, 46.76211117183027),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
map = new google.maps.Map(document.getElementById('mppp'), options);
infowindow = new google.maps.InfoWindow();
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds();
//******* ARRAY BROUGHT OVER FROM SEARCHRESULTS.PHP **********
mapinfo = [ <?=$da?> ];
intTimer = setInterval("call_geocode();", 300);
}
function call_geocode() {
if( address_index >= mapinfo.length ) {
clearInterval(intTimer);
return;
}
geocoder.geocode({
location: new google.maps.LatLng(mapinfo[address_index][6], mapinfo[address_index][7])
}, (function(index) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Scale our bounds
bounds.extend(results[0].geometry.location);
var $id = mapinfo[index][0];
var $tell = mapinfo[index][3];
var $title = mapinfo[index][2];
var $img_src = mapinfo[index][3];
var img_src = mapinfo[index][1];
var $logo = mapinfo[index][4];
var $status = mapinfo[index][5];
var $sell = mapinfo[index][6];
var $city = mapinfo[index][8];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(mapinfo[index][6], mapinfo[index][7]),
icon: {
url : '<? bloginfo('url'); ?>' + img_src + '',
scaledSize : new google.maps.Size(50,50)
},
map: map,
scrollwheel: false,
streetViewControl: true,
title: $title
});
google.maps.event.addListener(marker, 'click', function() {
// Setting the content of the InfoWindow
if (img_src) {
var imdd = '<img src="<? bloginfo('url'); ?>' + img_src + '" width="60" height="60" style="margin-left:4px;float:right;" />';
}
else {
var imdd = '';
}
if ($tell) {
var tell = 'رقم الهاتف : '+$tell+'<br>';
}
else {
var tell = '';
}
if ($status) {
var status = 'الحي : '+$status+'<br>';
}
else {
var status = '';
}
if ($city) {
var city = 'المدينة : '+$city+'<br>';
}
else {
var city = '';
}
var content = '<div id="info" style="direction:rtl;font:15px time new roman;font-weight:bolder;position:relative;width:210px;"><div style=" font-size:13px;font-family:Tahoma;font-weight:bolder;text-align:center;font-weight:bold">' + $title + '</div><br><div style="float:right">' + imdd + '</div><div style="float:right;text-align:right;font-family:Tahoma">' + tell + city + status + '</div><br /><a style="float:left;color:#d22f00;font-size:12px;font-family:Tahoma" href="<? bloginfo('url'); ?>/rest-det/?id=' + $id + '">المزيد+</a></div>';
infowindow.setContent(content);
infowindow.open(map, marker);
});
map.fitBounds(bounds);
if (mapinfo.length == 1) {
map.setZoom(12);
}
}
else {
// error!! alert (status);
}
}
}
)(address_index)
);
address_index++;
}
</script>
<div id="mppp" class="map"></div>
You can use an AJAX pattern to refresh part of your page.
move your SQL code into another script - e.g. query.php
return a list of results in a JSON format
when the list changes call runQuery
use the function to parse the returned data and update your map
<script>
function runQuery() {
$.ajax({
url: "query.php?type="+ $("#type").val(),
cache: false,
success: function(data){
// code to process your results list;
}
});
}
</script>
This is an AJAX concept where you are able to change only a portion of your page without having to do a full page refresh or Postback.
You will find a ton of examples on what you are trying to do but the main concept is that you will:
-Take user input
-call back to your server with values
-have the server return you information that you then use to append or overwrite a portion of the page

JSON Encoding a MySQL Array and Displaying on Google Map

I have been working on a little app for a friend right now I am encoding a mysql query with
<?php
include 'dbconnect.php';
$result = mysql_query("SELECT * FROM coords ORDER BY name DESC") or die ("Could not
query");
while($row = mysql_fetch_array($result)) {
$r[] = array(
"name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance']
);
}
$encoded = json_encode($r);
echo$encoded;
mysql_close($conn);
?>
The problem is there is no array position key associated with each entry to tell the json that this whole thing is a key
Array(
[1] = ( "name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance']),
[2] = ( "name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance'])));
for every row in the database basically I want to parse each row of the database into an array with his own key so i can call it as a javascript object and draw it ona google map.
ive tried
<?php
include 'dbconnect.php';
$count = 0;
$result = mysql_query("SELECT * FROM coords ORDER BY name DESC") or die ("Could not
query");
while($row = mysql_fetch_array($result)) {
$count = $count + 1;
$r[$count] = array(
"name" => $row['name'],
"lat" => $row['lat'],
"lng" => $row['lng'],
"speed" => $row['speed'],
"altitude" => $row['altitude'],
"distance" => $row['distance']
);
}
$encoded = json_encode($r);
echo$encoded;
mysql_close($conn);
?>
but that didn't work and theen there is my json code im not sure its right. Below is my map code can you look at the section of the json code and tellme if that is how im supposed to call the array I want to write in my php file. Also if I'm drawing the marker right fro the array. Thanks
var watchID;
var latitudeAndLongitudeCurrent;
var route = false;
var firstMapCall;
var directionsDisplay; // Declare a variable
of renderer object
var directionsService = new google.maps.DirectionsService(); // Instantiate a
directions service.
var map;
var currentMarker;
var carMarker;
var usermarker;
var markloc;
var myOptions =
{
zoom:14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
enableHighAccuracy: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
maximumAge: 10000
};
function initializeMyMap()
{
directionsDisplay = new google.maps.DirectionsRenderer(); // Instantiate a
renderer object.
//directionsDisplay.suppressMarkers = true; //removes direction markers
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map); // bind the map to
the renderer
}
function showLocation(){
firstMapCall = true;
//if initalize hasn't been called, call it
if(directionsDisplay == null) {
initializeMyMap();
}
watchID = navigator.geolocation.watchPosition(onSuccessShowLoc, onError, myOptions);
}
function setMapBounds(position){
var mapBounds = new google.maps.LatLngBounds();
mapBounds.extend(position);
map.fitBounds(mapBounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(18);
}
});
resize();
}
// onSuccess Geolocation
function onSuccessShowLoc(position) {
latitudeAndLongitudeCurrent = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
if(firstMapCall == true){
var result = retrieveLocation();
setMapBounds(latitudeAndLongitudeCurrent);
if(result != null){
addCarMarker(result);
}
firstMapCall = false;
}
deleteOverlays();
addCurrentLocMarker(latitudeAndLongitudeCurrent);
//ajax
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// This sets the users location in the database
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var parseid = id;
var queryString = "?lat=" + lat ;
queryString += "&lng=" + lng + "&id=" + parseid;
console.log('string combination');
ajaxRequest.open("GET", "data.php" + queryString, true);
ajaxRequest.send(null);
console.log('executed');
}
// Removes the overlays from the map, but keeps them in the array
function deleteOverlays() {
if (currentMarker) {
currentMarker.setMap(null);
}
}
function deleteCarOverlay() {
if (carMarker) {
carMarker.setMap(null);
}
}
function deleteUserOverlay() {
if (usermarker) {
usermarker.setMap(null);
}
}
function addCurrentLocMarker(location) {
marker = new google.maps.Marker({
position: location,
icon: 'http://www.wolfdoginfo.net/app/snowboarding.png',
map: map
});
currentMarker = marker;
}
function addCarMarker(location) {
marker = new google.maps.Marker({
draggable: true,
raiseOnDrag: false,
icon:'http://www.wolfdoginfo.net/app/revolt.png',
map: map,
position: location
});
carMarker = marker;
}
var myVar=setInterval(function(){showData()},3000);
function showData(str)
{
calluserlocation();
}
function calluserlocation(){
console.log('calluserlocation fires');
$.ajax( {
url: "getdata.php",
type: "GET",
dataType: "json",
success: function(data) { for (var i = 0; i < data.length; i++) { markloc = new
google.maps.LatLng(data[i].b, data[i].c); adddata(markloc); } }, error:
function(data) { console.log( "error with the json" ); } });
console.log("sucessful run of function");
}
function adddata(markloc){
marker = new google.maps.Marker({
position: markloc,
icon: 'http://www.wolfdoginfo.net/app/cropcircles.png',
map: map
});
deleteUserOverlay();
usermarker = marker;
}
function calcRoute()
{
var theDestination = retrieveLocation();
if(theDestination == null){
alert("Error: No Friend meeting place has been saved.");
return null;
}
var request = // Instantiate a DirectionsRequest object
{
//origin is LatLng object
origin: latitudeAndLongitudeCurrent,
//destination is LatLng object
destination: theDestination,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, // call route() to request directions service
function(result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setOptions({ preserveViewport: true });
directionsDisplay.setDirections(result); // draw the routes
// put text directions on directions_panel
directionsDisplay.setPanel(document.getElementById("directions_panel"));
route=true;
}
}
);
}
function textDirections()
{
if(route == false){
calcRoute();
}
}
function resize(){
var map_page = document.getElementById('show');
var map_container = document.getElementById('the_map_container');
var header = document.getElementById('thehead');
var newHeight = map_page.offsetHeight - 170;
map_container.style.height = newHeight + 'px';
// trigger a resize event on the map so it reflects the new size
if(map != null) {
google.maps.event.trigger(map, 'resize');
}
}
If you want your name as the key then do this
$r = array(); // A best practice to declare it's an array
while($row = mysql_fetch_assoc($result)) { // fetch_assoc gives you keys based on your field names
$r[$row['name']] = array( ... );
}
Also, a PSA, be sure to use mysqli as mysql has been depreciated.

Categories