javascript - Placing Geolocated Coordinates in a jQuery File -
i having difficulty inserting geolocated coordinates (latitude , longitude) of current user's location php/mysql generated xml file. requires user's geolocation correctly generate 20 closest businesses within 30-mile radius. using jquery-powered store locator script generate map. script works fine static url xmllocation, when try use variables in url outputs undefined alert message. aim javascript place latitude , longitude values of user's location php variables xml generator can generate correct output. looks this:
locationglobal = 'data/gen_default_map.php?lat=' + lat + '&lng=' + lon + '&radius=30';
and should ouput this:
data/gen_default_map.php?lat=34.383747&lng=-82.364574&radius=30
i have made modifications script , placed comments accordingly. need concern first 42 lines of code, in case here script in it's entirety:
/* user's current location , place in 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', <--- commented static url works 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 passed in origin locations in [_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); }); (var = 0; < destcoordarr.length; = + settings.googledistancematrixdestinationlimit) { // google distance matrix allows 25 destinations 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" 123.45 function googlemapdistancetexttonumber(str) { return number(str.replace(/[^0-9.]/g, "")); } // removes google maps url unfriendly chars string function formatgooglemapurlstring(str) { return str.replace("&", "%26").replace(" ", "+"); } //geocode function 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 not successful 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 not successful following reason: " + status); callbackfunction(null); } }); }; } //process form input $(function () { $(document).on('submit', '#' + settings.formid, function (e) { $("#lblerror").html(""); //stop form submission e.preventdefault(); //get user input , use 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 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 geocode handlenogeolocation('error: unable geocode address'); } }); // mapping stuff mapping(position.coords.latitude, position.coords.longitude); }, function () { handlenogeolocation("tracking of location not allowed."); }); } else { // browser doesn't support geolocation handlenogeolocation(false); } }); function showaddress(address) { $("#lbladdress").html(address.formatted_address); // find postcode , show in address textbox $.each(address.address_components, function (i, val) { if (val.types[0] == "postal_code") { $("#address").val(val.short_name); return false; // breaks each() loop } }); } function handlenogeolocation(error) { if (error) { var content = error; } else { var content = 'error: 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 mapping stuff function mapping(orig_lat, orig_lng) { $(function () { //parse xml 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 lat lng 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 user's location geocodecalc.calcdistancegoogle(new google.maps.latlng(orig_lat, orig_lng), function (success) { if (!success) { //something went wrong handleerror("unable calculate distances @ time"); } else { //sort 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 closest marker if (_locationset[0].distance > settings.distancealert) { handleerror("unfortunately, our closest location more " + settings.distancealert + " miles away."); } //create map 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 1 infowindow 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 show 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\">» directions</a><\/div><\/div><\/div>") .click(function () { create_infowindow(shop, "left"); }).appendto("#" + settings.listdiv); }; //custom marker function - aplhabetical function createmarker(point, letter, pincolor) { //set pin icon google charts api 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 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 pin icon google charts api of our markers var pinimage = new google.maps.markerimage("images/green_pin.png"); //create markers return new google.maps.marker({ position: point, map: map, title: "your location", icon: pinimage, draggable: false }); }; //infowindows function create_infowindow(shop, listlocation) { //is distance more 1 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 infowindow when list item clicked if (listlocation == "left") { infowindow.setcontent(formattedaddress); infowindow.open(shop.marker.get(settings.mapdiv), shop.marker); } //opens infowindow when marker 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 need xmllocation dynamically geolocated url. seems variable not being set correctly. undefined error message when try call locationglobal. have speculated on issue , have hit dead end it. appreciated. thanks.
the alert shows undefined
because of callback nature of getcurrentlocation()
operation. have call locationglobal
dependent function inside callback function of getcurrentlocation()
operation. 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 example });
hope helps.
Comments
Post a Comment