I want to print out the coordinates calculated by a geocoding javascript ( maded with Google api V3 ), how can i do that??
and then, how can i pass this values to two variables ($Lat and $Long) that are in a php file that generate a google map maded in Api V2 ??
thanks.
this is my javascript code:
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=HERE MY API KEY" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://code.google.com/apis/gears/gears_init.js"></script>
<script type="text/javascript">
function getLocale(){
if ( navigator ) {
if ( navigator.userLanguage ) {
return navigator.userLanguage.toLowerCase();
}
else if ( navigator.language ) {
return navigator.language.toLowerCase();
}
else if ( navigator.browserLanguage ) {
return navigator.browserLanguage.toLowerCase();
}
else if ( navigator.systemLanguage ) {
return navigator.systemLanguage.toLowerCase();
}
}
return "unknown";
}
var locales = new Object();
locales["en-gb"] = {lat:54.559322587438636, lng:-4.1748046875, location:"United Kingdom"};
locales["en-us"] = {lat:38.41055825094609, lng:-100.37109375, location:"USA"};
// TODO - more locales
function showMap(latLong, zoom){
var options = {
zoom: zoom,
center: latLong,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position: latLong,
map: map,
title:"Your location"
});
}
function TryGoogleLoader(){
if (google.loader.ClientLocation != null) {
var address = google.loader.ClientLocation.address;
var yourLocation = address.city + ", " + address.region + ", " + address.country;
document.getElementById("location").innerHTML = "Your location (using Google loader) is " + yourLocation;
var latLong = new google.maps.LatLng(google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude);
showMap(latLong, 12);
}
else {
// map locale to location
var locale = getLocale();
if (locales[locale] != null) {
var latLong = new google.maps.LatLng(locales[locale].lat, locales[locale].lng);
document.getElementById("location").innerHTML =
"Guessing your location based on your locale - " + locales[locale].location;
showMap(latLong, 5);
}
else {
document.getElementById("location").innerHTML = "Your location can not be found - locale is " + locale;
}
}
}
function TryGoogleGears(){
if (google.gears) {
// Try Google Gears Geolocation
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
var latLong = new google.maps.LatLng(position.latitude, position.longitude);
document.getElementById("location").innerHTML = "Found location via Google Gears";
showMap(latLong, 15);
}, function() {
TryGoogleLoader();
});
}
else
TryGoogleLoader();
}
window.onload = function() {
// try W3C standard approach
var geoTimeout = 10000;
var timeOuthandler = setTimeout("TryGoogleGears()", geoTimeout);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
clearTimeout(timeOuthandler);
var latLong = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
document.getElementById("location").innerHTML = "Found location via W3C standard";
showMap(latLong, 15);
}, function() {
// something went wrong, try Google Gears
clearTimeout(timeOuthandler);
TryGoogleGears();
}, {timeout:geoTimeout});
}
else
TryGoogleGears();
}
</script>
how can i print with an alert code the value of the "var latLong"?
how can i pass this value to a set of php variables like $lat and $long?
thanks.
On the W3C function you could do this on success
document.getElementById("location").innerHTML = position.coords.latitude +", "+position.coords.longitude;
On the TryGoogleGears function you could do this on success
document.getElementById("location").innerHTML = position.latitude +", "+position.longitude;
In order to pass the LatLong pair back to PHP you will need to use a XMLHTTPRequest or something similar. This is because PHP is a server side script that executes before JavaScript does, which runs on the client. So to tell PHP something you need to either load a new page and pass the data from JavaScript to PHP with headers, GET, or POST variables. You can either load this page the normal way in the browser and your users see a redirect or you can load it in the background using XMLHTTPRequest.
Related
I've got an issue that I can't fix, it's been weeks I'm trying to do so but I just can't figure out what I'm doing wrong, or if there's something wrong in the Parse PHP SDK.
I have built a website with Parse Server as the backend, it's a listing website with location detection, and I'm working on Chrome (I've tried Firefox and Safari as well, I get the same issue).
My steps:
When you got to the home page, the browser asks you to allow location detection, I allow it.
If you click on the location button, you can open a Google map into a modal and place the pin on click to the desired location, you can also set the distance range by moving a slider. I select London, UK
I get the right console messages in Chrome:
DISTANCE: 87 Km
MARKER LAT: 51.522497992110246 - MARKER LNG: -0.12863733794108612
The issue comes here, the website shows only some of the posted Ads, those ones that I have posted through a mobile app (my own source code too, with Parse iOS and Android SDKs), it doesn't display those ads I've submitted through the website. Weird thing, if I post ads from the website and I open my mobile app, I can see them!
And if I check my database, the GeoPoint coordinates of my ads are correctly stored, whether I submitted ads through the website or the mobile apps.
Lastly, If I perform a search by keywords with the search bar on the top of the page, I can find those ads I've posted through the website. So, basically, no keywords, no ads posted through the website...
Here's my PHP code to query ads (NOTE; the variables that start with $ADS_ are simple strings declared in another file, ex. $ADS_LOCATION = "ads_location", etc):
/*--- variables ---*/
$isFollowing = $_GET['isFollowing'];
$option = $_GET['option'];
$upObjID = $_GET['upObjID'];
$latitude = $_GET['lat']; // 51.522497992110246
$longitude = $_GET['lng']; // -0.12863733794108612
$dist = $_GET['distance'];
$distance = (int)$dist; // 50
$category = $_GET['category'];
$sortBy = str_replace(' ', '', $_GET['sortBy']);
$keywords = preg_split('/\s+/', $_GET['keywords']);
// query Ads
try {
$query = new ParseQuery($ADS_CLASS_NAME);
$query->equalTo($ADS_IS_REPORTED, false);
// it's following.php
if ($isFollowing == true) {
$currentUser = ParseUser::getCurrentUser();
$cuObjIdArr = array();
array_push($cuObjIdArr, $currentUser->getObjectId());
$query->containedIn($ADS_FOLLOWED_BY, $cuObjIdArr);
// it's User profile page
} else if ($upObjID != null) {
$userPointer = new ParseUser($USER_CLASS_NAME, $upObjID);
$userPointer->fetch();
$query->equalTo($ADS_SELLER_POINTER, $userPointer);
if ($option == 'selling'){ $query->equalTo($ADS_IS_SOLD, false);
} else if ($option == 'sold'){ $query->equalTo($ADS_IS_SOLD, true);
} else if ($option == 'liked'){ $query->containedIn($ADS_LIKED_BY, array($userPointer->getObjectId())); }
// it's index.php
} else {
// nearby Ads
if ($latitude != null && $longitude != null) {
$currentLocation = new ParseGeoPoint($latitude, $longitude);
$query->withinKilometers("location", $currentLocation, $distance);
// nearby DEFAULT LOCATION COORDINATES
} else {
$defaultLocation = new ParseGeoPoint($DEFAULT_LOCATION_LATITUDE, $DEFAULT_LOCATION_LONGITUDE);
$query->withinKilometers($ADS_LOCATION, $defaultLocation, $DISTANCE_IN_KM);
}
// keywords
if (count($keywords) != 0) { $query->containedIn($ADS_KEYWORDS, $keywords); }
// category
if ($category != "All") { $query->equalTo($ADS_CATEGORY, $category); }
// sort by
switch ($sortBy) {
case 'Newest': $query->descending("createdAt");
break;
case 'Price:lowtohigh': $query->ascending($ADS_PRICE);
break;
case 'Price:hightolow': $query->descending($ADS_PRICE);
break;
case 'MostLiked': $query->descending($ADS_LIKES);
break;
default: break;
}// ./ sort by
}// ./ If
// perform query
$adsArray = $query->find();
if (count($adsArray) != 0) {
for ($i = 0; $i < count($adsArray); $i++) {
// Parse Obj
$adObj = $adsArray[$i];
// image 1
$adImg = $adObj->get($ADS_IMAGE1);
// title
$adTitle = substr ($adObj->get($ADS_TITLE), 0, 24).'...';
// currency
$adCurrency = $adObj->get($ADS_CURRENCY);
// price
$adPrice = $adObj->get($ADS_PRICE);
echo '
<!-- Ad card -->
<div class="col-lg-3 col-md-5 portfolio-item">
<div class="card">
';
// Sold badge
$isSold = $adObj->get($ADS_IS_SOLD);
if ($isSold) { echo '<div class="card-sold-badge"><img src="assets/images/sold-badge.png"></div>'; }
echo '
<img src="'.$adImg->getURL().'">
<div class="card-body">
<p class="card-title">'.$adTitle.'</p>
<p class="card-price">'.$adCurrency.' '.$adPrice.'</p>
</div>
</div>
</div>
';
}// ./ For
// no ads
} else {
echo '
<div class="col-lg-12 col-md-12">
<div class="text-center" style="margin-top: 40px; font-weight: 600">No Ads found.</div>
</div>
';
}
// error
} catch (ParseException $e){ echo $e->getMessage(); }
The above code comes from a separate file called query-ads.php and it gets displayed in a div:
<div class="row" id="adsGrid"></div>
I perform an AJAX function to call query-ads.php:
function queryAds(catName, keywords) {
// category
if (catName == null) { catName = "All"; }
document.getElementById("categoryName").innerHTML = '<h5 id="categoryName"><strong>' + catName + '</strong></h5>';
// keywords
if (keywords == null) { keywords = ''; }
// console.log('KEYWORDS: ' + keywords);
// console.log('LAT: ' + latitude + ' -- LNG: ' + longitude);
console.log('DISTANCE: ' + distance + ' Km');
// console.log('SORT BY: ' + sortBy);
$.ajax({
url:'query-ads.php',
data: 'lat=' + latitude + '&lng=' + longitude + '&distance=' + distance + '&category=' + catName + '&keywords=' + keywords + '&sortBy=' + sortBy,
type: 'GET',
success:function(data) {
document.getElementById("adsGrid").innerHTML = data;
},
// error
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
swal(err.Message);
}});
}
And here's my JavaScript code as well:
var cityStateButton = document.getElementById("cityState");
/*--- variables --*/
// localStorage.clear();
var latitude = localStorage.getItem('latitude');
var longitude = localStorage.getItem('longitude');
var distance = localStorage.getItem('distance');
if (distance == null) { distance = 50; }
var map;
var markers = [];
var geocoder;
var sortBy = document.getElementById('sortByBtn').innerHTML;
console.log("1st LATITUDE: " + latitude + " -- 1st LONGITUDE: " + longitude + ' -- 1st DISTANCE: ' + distance + ' -- 1st SORT BY: ' + sortBy);
// Call functions
if (latitude == null) { getCurrentLocation();
} else { getAddress(); }
// ------------------------------------------------
// MARK: - GET CURRENT LOCATION
// ------------------------------------------------
function getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition, showError);
} else {
swal("Geolocation is not supported by this browser.");
// set default location coordinates
latitude = <?php echo $DEFAULT_LOCATION_LATITUDE ?>;
longitude = <?php echo $DEFAULT_LOCATION_LONGITUDE ?>;
getAddress();
}
}
function getPosition(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
getAddress();
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
swal("You have denied your current Location detection.");
break;
case error.POSITION_UNAVAILABLE:
swal("Location information is unavailable.");
break;
case error.TIMEOUT:
swal("The request to get your current location timed out.");
break;
case error.UNKNOWN_ERROR:
swal("An unknown error occurred.");
break;
}
// set default location
latitude = <?php echo $DEFAULT_LOCATION_LATITUDE ?>;
longitude = <?php echo $DEFAULT_LOCATION_LONGITUDE ?>;
getAddress();
}
function getAddress () {
// geocoding API
var geocodingAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&key=<?php echo $GOOGLE_MAP_API_KEY ?>";
$.getJSON(geocodingAPI, function (json) {
if (json.status == "OK") {
var result = json.results[0];
var city = "";
var state = "";
for (var i = 0, len = result.address_components.length; i < len; i++) {
var ac = result.address_components[i];
if (ac.types.indexOf("locality") >= 0) { city = ac.short_name; }
if (ac.types.indexOf("country") >= 0) { state = ac.short_name; }
}// ./ For
// show city, state
cityStateButton.innerHTML = '<i class="fas fa-location-arrow"></i> ' + city + ', ' + state;
// call query
queryAds();
// save gps coordinates
localStorage.setItem('latitude', latitude);
localStorage.setItem('longitude', longitude);
// console.log("LAT (getAddress): " + latitude + " -- LNG (getAddress): " + longitude);
// call function
initMap();
}// ./ If
});
}
//---------------------------------
// MARK - INIT GOOGLE MAP
//---------------------------------
var mapZoom = 12;
function initMap() {
var location = new google.maps.LatLng(latitude, longitude);
map = new google.maps.Map(document.getElementById('map'), {
zoom: mapZoom,
center: location,
mapTypeId: 'roadmap',
disableDefaultUI: true,
mapTypeControl: false,
scaleControl: false,
zoomControl: false
});
// call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Add a marker in the center of the map.
addMarker(location);
}
function addMarker(location) {
clearMarkers();
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
// set lat & lng based on marker's coordinates
latitude = marker.getPosition().lat();
longitude = marker.getPosition().lng();
console.log("MARKER LAT: " + latitude + " - MARKER LNG: " + longitude);
// zoom & center map based on pin
metersPerPx = 156543.03392 * Math.cos(latitude * Math.PI / 180) / Math.pow(2, mapZoom)
map.setZoom(metersPerPx/2.6);
map.setCenter(marker.getPosition());
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}// ./ For
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
markers = [];
}
//---------------------------------
// MARK - GET GPS COORDS FROM ADDRESS
//---------------------------------
function getCoordsFromAddress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markers.push(marker);
// set coordinates
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
// save gps coordinates
localStorage.setItem('latitude', latitude);
localStorage.setItem('longitude', longitude);
// console.log("SEARCH LOCATION LAT: " + latitude + " - SEARCH LOCATION LNG: " + longitude);
initMap();
// error
} else { swal('Geocode was not successful for the following reason: ' + status);
}});
}
I thought it was an issue with ParseGeoPoint, but it's not, because if I make a text search for keywords, I can find Ads.
Found the solution, I'm posting it just in case someone else will encounter such issue on the Parse PHP SDK, because it's there since early 2018.
In my script that saves Ads in my database, I was storing lowercase keywords based on the description and title of submitted items:
$kStr = $description. " " .$title. " " .$currentUser->getUsername();
$keywords = explode( " ", strtolower($kStr) );
Which was working fine, but since the PHP ParseQuery with a keywords filter needs at least an empty item in the array of keywords, I had to add this simple line below the above code:
array_push($keywords, "");
In this way, the database stores all proper keywords + an empty one: "", here's an example of how the keywords Arrat-type field looks like in the database:
[
"lorem",
"ad",
"ipsum",
"johndoe",
"" <-- this is the empty item that the SDK needs to properly perform a query in case of additional filters (in my case, a ParseGeopoint one)
]
This may be just a temporary trick until Parse Server's developers will fix this issue. It works, so why not ;)
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
I am having difficulty inserting the geolocated coordinates (latitude and longitude) of the current user's location into a PHP/MySQL generated xml file. It requires the user's geolocation to correctly generate the 20 closest businesses within a 30-mile radius. I am currently using a jQuery-powered store locator script to generate the map. The script works fine with a static URL as the xmlLocation, but when I try to use variables in the URL it just outputs an undefined alert message. My aim is to get javascript to place the latitude and longitude values of the user's location into the PHP GET variables so that the XML generator can generate correct output. It looks like this:
LocationGlobal = 'data/gen_default_map.php?lat=' + lat + '&lng=' + lon + '&radius=30';
And should ouput something like this:
data/gen_default_map.php?lat=34.383747&lng=-82.364574&radius=30
I have made modifications to the script and placed comments accordingly. You probably only need to concern yourself with the first 42 lines of the code, but just in case here is the script in it's entirety:
/* Get the User's Current Location and place it in the URL */
/*--------------------------------------------------*/
var LocationGlobal;
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lon = position.coords.longitude;
LocationGlobal = 'data/gen_default_map.php?lat=' + lat + '&lng=' + lon + '&radius=30';
alert(LocationGlobal); // Sets correctly here
return LocationGlobal;
});
} else {
console.log('Error getting coordinates.');
}
alert(LocationGlobal); // Undefined here
/*--------------------------------------------------*/
(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': LocationGlobal, //'data/gen_default_map.php?lat=34&lng=-82&radius=30', <--- the commented static URL works but variable doesn't
'addressErrorMsg': 'Please enter valid address address or postcode',
'googleDistanceMatrixDestinationLimit': 25,
'defaultLat': 34.8483680,
'defaultLng': -82.400440,
'defaultLocationName': 'Greenville, South Carolina'
}, 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, our closest location is more than " + settings.distanceAlert + " miles away.");
}
//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 = createUserMarker(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);
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-label\">" + letter + "<\/div><div class=\"list-content\">"
+ "<div class=\"loc-name\">" + shop.Name + "<\/div> <div class=\"loc-addr\">" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div class=\"loc-addr2\"><i>approx. " + shop.Distance + " " + ((shop.Distance == 1) ? "mile" : "miles" ) + "</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
});
};
//Custom marker function - aplhabetical
function createUserMarker(point, letter, pinColor) {
//Set up pin icon with the Google Charts API for all of our markers
var pinImage = new google.maps.MarkerImage("images/green_pin.png");
//Create the markers
return new google.maps.Marker({
position: point,
map: map,
title: "Your Location",
icon: pinImage,
draggable: false
});
};
//Infowindows
function create_infowindow(shop, listLocation) {
//Is the distance more than one mile?
if (shop.Distance == 1) {
var mi_s = "mile";
} else {
var mi_s = "miles";
}
var formattedAddress = "<div class=\"infoWindow\"><b>" + shop.Name + "<\/b>"
+ "<div>" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div><i>" + shop.Distance + " " + mi_s + "<\/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);
Under var settings I need xmlLocation to be the dynamically geolocated URL. It seems the variable is not being set correctly. I get an undefined error message when I try to call LocationGlobal. I have speculated on this issue and have hit a dead end with it. Any help is greatly appreciated. Thanks.
The alert shows undefined because of the callback nature of the getCurrentLocation() operation. You have to call the LocationGlobal dependent function from inside the callback function of the getCurrentLocation() operation. probably like,
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lon = position.coords.longitude;
LocationGlobal = 'data/gen_default_map.php?lat=' + lat + '&lng=' + lon + '&radius=30';
alert(LocationGlobal);
$('#map').storeLocaor({ mapDiv: 'map', xmlLocation: LocationGlobal }); //Just an example
});
hope this helps.
This is javascript function to access latitude longitude and city from json:
function parse()
{
var json = '<?php echo $json; ?>';
var events = jQuery.parseJSON(json);
var DateArray = new Array();
var size = Object.keys(events).length;
search(events);
}
function search(events)
{
for ( i in events)
{
if( typeof events[i] === 'object' )
{
key= i.toLowerCase();
if(key.indexOf("latitude") !== -1)
{
var lat = events[i];
var longi = events['longitude'];
// alert(lat + longi);
initialize(lat,longi,'5');
// DateArray = DateArray.concat(events[i]);
// alert('DataArray');
}
search(events[i]);
}
}
}
I have this json:
{
"type":"http://schema.org/Place",
"class":"place",
"city":"London",
"geo":{
"type":"http://schema.org/GeoCoordinates",
"class":"geocoordinates",
"latitude":"30",
"longitude":"70"
}
}
map code:
function initialize(a,b,zom){
if (!a || !b ||!zom){
var centerLoc=new google.maps.LatLng( 34.61701054652337,71.37824736488983);
zoom=16;
}
else
{
alert(typeof a + typeof b + typeof zom);
var zoom =parseInt(zom);
var centerLoc=new google.maps.LatLng(a,b);
alert('it works fine');
}
var mapProp = {
center:centerLoc,
zoom:zoom,
//mapTypeId:google.maps.MapTypeId.ROADMAP
mapTypeId:google.maps.MapTypeId.SATELLITE
};
var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
marker=new google.maps.Marker({
position:centerLoc,
title:'Click to zoom'
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(map.getZoom()+1);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
}
google.maps.event.addDomListenerOnce(window, 'load', initialize);
When lat long and city are initialized, initialized function is called with lat and long as parameters.
problem
When arguments are passed to initialize function to initialize google map, it shows that function is called as it alerts the values of parameters in called function.lat and long both are string of type as required. but this does not show google map.
I had the following HTML page rendering to use the Google Maps API. This has been running for about two months and all the sudden just stopped working. I am trying to get the point with the getLatLng function and it appears to be returning null everytime. Has anyone experienced a similar issue or see anything wrong here? Any help is appreciated.
Using Version 2 of the API. ("v=2")
var map = null;
var geocoder = null;
var marker;
var g_address = "1 Yawkey Way Boston MA";
var toggleState = 0;
var toggleStateDir = 0;
var mapDir;
var gDir;
var geocoderDir = null;
var markerDir;
var g_addressDir = "100 Commonwealth Ave Boston MA";
var panorama;
var currentYaw = 180;
var currentPitch = 0;
var currentZoom = 0;
function initialize()
{
if (GBrowserIsCompatible())
{
// Map
document.getElementById("address").value = g_address;
document.getElementById("addressDir").value = g_addressDir;
map = new GMap2(document.getElementById("map_canvas"));
map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());
map.addControl(new GLargeMapControl3D());
// Street View
geocoder = new GClientGeocoder();
panorama = new GStreetviewPanorama(document.getElementById("pano"));
// Directions
mapDir = new GMap2(document.getElementById("map_canvas_dir"));
gDir = new GDirections(mapDir, document.getElementById("directions"));
mapDir.addControl(new GMapTypeControl());
mapDir.addControl(new GScaleControl());
mapDir.addControl(new GLargeMapControl3D());
// Traffic overlay
map.setUIToDefault();
var trafficOptions = { incidents: true };
trafficInfo = new GTrafficOverlay(trafficOptions);
mapDir.setUIToDefault();
var trafficOptionsDir = { incidents: true };
trafficInfoDir = new GTrafficOverlay(trafficOptionsDir);
showAddress(g_address, g_addressDir);
}
}
function showAddress(address, addressDir)
{
if (geocoder)
{
geocoder.getLatLng(address,
function(point) {
if (!point) {
alert(address + " not found" + response.Status.code);
}
else {
// Map
g_address = address
map.setCenter(point, 15);
marker = new GMarker(point);
map.addOverlay(marker);
// Street View
document.getElementById("lat").value = point.y;
document.getElementById("long").value = point.x;
document.getElementById("pano").removeAttribute("pano");
panorama.setLocationAndPOV(new GLatLng(point.y, point.x), { yaw: currentYaw, pitch: currentPitch, zoom: currentZoom });
// Directions
gDir.load("from: " + addressDir + " to: " + address, { "locale": "en_US" });
}
}
);
}
}
There's nothing wrong with that code. It works perfectly for me.
Unfortunately, .getLatLng() doesn't return an error code when it fails, and this line will crash when .getLatLng returns nothing:
alert(address + " not found" + response.Status.code);
I can't guess whether there's a problem with your API key (error 610) or if you've been blocked for making too many geocode requests (error 620). I strongly suspect that it will be one of those two because any other error code would be expected to cause the code to fail when I try it.
Try changing your (!point) code to
if (!point) {
geocoder.getLocations(address, function(response) {
alert(address + " not found: " + response.Status.code);
});
}
which uses .getLocations() on the same address and displays the error code.