take out location from geocoder function [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
im trying to assign the value of my address to another variable but all i get is undefined or something like my url in the variable
here is my coding. i almost crack my head because of this.
function geoCoding(displayname, trackerModel, setupType, marker, index){
var setupMessageInfoWindow;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var location = results[1].formatted_address;
} else {
alert('No results found at marker ' + marker.position);
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
setupMessageInfoWindow = "<div height=\"300\" width=\"300\"><b>" + displayname + "</b>"
+ " <br> Location : " + location
//+ " <br> Tracker id : " + userid
//+ " <br> imei : " + imei
+ " <br> Tracker Type : " + trackerModel
//+ " <br> Mobile Number : " +
//+ " <br> Location : " + location;
+ " <br> " + setupType
+ "</div>" ;
return setupMessageInfoWindow;
}

geocode is asynchronous so setupMessageInfoWindow variable is created before variable location is properly set. If you want to set some info window you can call a function from geocode() when location is successfully retrieved. For example:
function setContent(marker, content) {
infoWin.setContent(content);
google.maps.event.addListener(marker, 'click', function() {
infoWin.open(map, marker);
});
}
function geoCoding(displayname, trackerModel, setupType, marker, index){
var setupMessageInfoWindow;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('status ok');
console.log(results);
if (results[1]) {
var location = results[1].formatted_address;
setupMessageInfoWindow = "<div height=\"300\" width=\"300\"><b>" + displayname + "</b>"
+ " <br> Location : " + location
//+ " <br> Tracker id : " + userid
//+ " <br> imei : " + imei
+ " <br> Tracker Type : " + trackerModel
//+ " <br> Mobile Number : " +
//+ " <br> Location : " + location;
+ " <br> " + setupType
+ "</div>" ;
setContent(marker, setupMessageInfoWindow);
} else {
console.log('No results found at marker ' + marker.position);
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}
See example at jsbin. There is click event handler set for marker which shows location found.

Related

Mapbox Javascript API function event call order

I am only attaching the script tag. Below is the flow of events that happen and the problem I see. I would appreciate any suggestions/advice.
I trigger the businessGeocoder by searching for an address, which triggers the businessAddress function inside the initialize function, which in turn triggers the businessLocationClickInfo function. This works perfectly.
Without refreshing the page I decide to use the employeeResidenceGeocoder by searching for an address, which triggers the employeeResidenceAddress function inside the initialize function, which in turn triggers the employeeResidenceLocationClickInfo function. This works perfectly. too.
Again, without refreshing the page I decide to use the businessGeocoder again by searching for an address, which triggers the businessAddress function inside the initialize function, which in turn SHOULD trigger the businessLocationClickInfo function, but instead, it triggers the employeeResidenceLocationClickInfo function. The employeeResidenceLocationClickInfo function, while it should have not been called, returns the correct data. I am having a hard time understanding why it is being called instead of the businessLocationClickInfo function.
Please note that doing it the other way, using employeeResidenceGeocoder first and then businessGeocoder, and then back to employeeResidenceGeocoder causes the same problem.
Update>> I ran console logs after each line and found out that because the click events are called in the initialize function, every time I click on the map both businessLocationClickInfo and employeeResidenceLocationClickInfo are being called, one replacing the other output div, whereas I want to only call one of them, depending on the geocoder. But I still haven't found a way/order to fix it.
<script>
var map;
var businessGeocoder;
var employeeResidenceGeocoder;
var businessLocationClickFeature;
var employeeResidenceLocationClickFeature;
var screenPoint;
var address;
var geocodeFeature;
var geocodePopup;
var geocodeCensusTract;
var geocodeCensusBlockGroup;
var businessLocationPolygon;
var employeeResidenceLocationPolygon;
function initialize() {
businessGeocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
flyTo: {
speed: 100
},
zoom: 17,
placeholder: "Search for a business location",
mapboxgl: mapboxgl
})
employeeResidenceGeocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
flyTo: {
speed: 100
},
zoom: 17,
placeholder: "Search for an employee's residence",
mapboxgl: mapboxgl
})
// // // adds geocoder outside of map (inside of map would make it a 'map control')
// document.getElementById('geocoder1').appendChild(businessGeocoder.onAdd(map));
// document.getElementById('geocoder2').appendChild(employeeResidenceGeocoder.onAdd(map));
map.addControl(businessGeocoder);
map.addControl(employeeResidenceGeocoder);
businessGeocoder.on('result', businessAddress);
employeeResidenceGeocoder.on('result', employeeResidenceAddress);
}
function businessAddress (obj) {
address = obj.result.place_name;
$(".geocode-result-area").html('<b>Geocoded Business Address: </b>' + address + '<br/><div class="medium-font">Click the blue address pin on the map for updated results.</div>');
$(".geocode-click-result-area").html("");
map.on('click', businessLocationClickInfo);
}
function employeeResidenceAddress (obj) {
address = obj.result.place_name;
$(".geocode-result-area").html('<b>Geocoded Employee Residence Address: </b>' + address + '<br/><div class="medium-font">Click the blue address pin on the map for updated results.</div>');
$(".geocode-click-result-area").html("");
map.on('click', employeeResidenceLocationClickInfo);
}
function businessLocationClickInfo (obj) {
businessLocationClickFeature = map.queryRenderedFeatures(obj.point, {
layers: ['tract-4332-1sbuyl','blockgroups-4332-9mehvk','businesslocation']
});
if (businessLocationClickFeature.length == 3) {
$(".geocode-click-result-area").html('<br/>This area meets the <span style="background-color:yellow">business location criteria</span> based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>' + businessLocationClickFeature[2].properties.Inquiry1 + '</td></tr>'
+ '<tr><td>CT & BG Poverty Rate ≥ 20%</td><td>' + businessLocationClickFeature[2].properties.Inquiry2 + '</td></tr></table>'
+ '<p><b>' + businessLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ businessLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ businessLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+'<table><tr><th></th><th>Poverty Rate</th></tr><tr><td>CT '
+ businessLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ businessLocationClickFeature[0].properties.PovRate + "%" + '</td></tr><tr><td>BG '
+ businessLocationClickFeature[1].properties.BLKGRPCE + '</td><td>'
+ businessLocationClickFeature[1].properties.PovRate + "%" + '</td></tr></table>'
);
}
else {
$(".geocode-click-result-area").html('<br/> This area <u style = "color:red;">does not</u> meet the business location criteria based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>No</td></tr>'
+ '<tr><td>CT & BG Poverty Rate ≥ 20%</td><td>No</td></tr></table>'
+ '<p><b>' + businessLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ businessLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ businessLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+ '<table><tr><th></th><th>Poverty Rate</th></tr><tr><td>CT '
+ businessLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ businessLocationClickFeature[0].properties.PovRate + "%" + '</td></tr><tr><td>BG '
+ businessLocationClickFeature[1].properties.BLKGRPCE + '</td><td>'
+ businessLocationClickFeature[1].properties.PovRate + "%" + '</td></tr></table>'
);
}
}
function employeeResidenceLocationClickInfo (obj) {
employeeResidenceLocationClickFeature = map.queryRenderedFeatures(obj.point, {
layers: ['tract-4332-1sbuyl','blockgroups-4332-9mehvk','employeeresidencelocation']
});
if (employeeResidenceLocationClickFeature.length == 3) {
$(".geocode-click-result-area").html('<br/>This area meets the <span style="background-color:yellow">employee residence location criteria</span> based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>' + employeeResidenceLocationClickFeature[2].properties.Inquiry1 + '</td></tr>'
+ '<tr><td>CT % LMI ≥ 70%</td><td>' + employeeResidenceLocationClickFeature[2].properties.Inquiry2 + '</td></tr>'
+ '<tr><td>CT & all BG Poverty Rate ≥ 20%</td><td>' + employeeResidenceLocationClickFeature[2].properties.Inquiry3 + '</td></tr></table>'
+ '<p><b>' + employeeResidenceLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ employeeResidenceLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ employeeResidenceLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+ '<table id="CensusTable"><tr><th></th><th>Poverty Rate</th><th>LMI</th></tr><tr><td>CT '
+ employeeResidenceLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.PovRate + "%" + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.LMIPerc + "%" + '</td></tr>');
var BGsin20PovertyCT = map.queryRenderedFeatures(
{ layers: ['blockgroups-4332-9mehvk'],
filter: ["==", "TRACTCE", employeeResidenceLocationClickFeature[0].properties.TRACTCE]
});
var unique = [];
var distinct = [];
for (let i = 0; i < BGsin20PovertyCT.length; i++ ){
if (!unique[BGsin20PovertyCT[i].properties.BLKGRPCE]){
distinct.push(BGsin20PovertyCT[i]);
unique[BGsin20PovertyCT[i].properties.BLKGRPCE] = 1;
}
}
for (let i = 0; i < distinct.length; i++ ){
$("#CensusTable").append('<tr><td>BG ' + distinct[i].properties.BLKGRPCE + '</td><td>'
+ distinct[i].properties.PovRate + "%" + '</td><td>-</td></tr></table>'
);
}
}
else {
$(".geocode-click-result-area").html('<br/> This area <u style = "color:red;">does not</u> meet the employee residence location criteria based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>No</td></tr>'
+ '<tr><td>CT % LMI ≥ 70%</td><td>No</td></tr>'
+ '<tr><td>CT & all BG Poverty Rate ≥ 20%</td><td>No</td></tr></table>'
+ '<p><b>' + employeeResidenceLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ employeeResidenceLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ employeeResidenceLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+ '<table id="CensusTable"><tr><th></th><th>Poverty Rate</th><th>LMI</th></tr><tr><td>CT '
+ employeeResidenceLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.PovRate + "%" + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.LMIPerc + "%" + '</td></tr>');
var BGsin20PovertyCT = map.queryRenderedFeatures(
{ layers: ['blockgroups-4332-9mehvk'],
filter: ["==", "TRACTCE", employeeResidenceLocationClickFeature[0].properties.TRACTCE]
});
var unique = [];
var distinct = [];
for (let i = 0; i < BGsin20PovertyCT.length; i++ ){
if (!unique[BGsin20PovertyCT[i].properties.BLKGRPCE]){
distinct.push(BGsin20PovertyCT[i]);
unique[BGsin20PovertyCT[i].properties.BLKGRPCE] = 1;
}
}
for (let i = 0; i < distinct.length; i++ ){
$("#CensusTable").append('<tr><td>BG ' + distinct[i].properties.BLKGRPCE + '</td><td>'
+ distinct[i].properties.PovRate + "%" + '</td><td>-</td></tr></table>'
);
}
}
}
mapboxgl.accessToken = 'pk.eyJ1Ijoia3l1bmdhaGxpbSIsImEiOiJjanJyejQyeHUyNGwzNGFuMzdzazh1M2k1In0.TcQEe2aebuQZ4G7d827A9Q';
map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/kyungahlim/ckd226uao1p7i1iqo8ag2ewmu',
center: [-95.925, 29.575],
zoom: 7
});
map.on('load', initialize);
// // Center the map on the coordinates of any clicked symbol from the 'symbols' layer.
// map.on('click', 'symbols', function(e) {
// map.flyTo({
// center: e.features[0].geometry.coordinates
// });
// });
// // Change the cursor to a pointer when the it enters a feature in the 'symbols' layer.
// map.on('mouseenter', 'symbols', function() {
// map.getCanvas().style.cursor = 'pointer';
// });
// // Change it back to a pointer when it leaves.
// map.on('mouseleave', 'symbols', function() {
// map.getCanvas().style.cursor = '';
// });
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-95.925, 29.575]
},
properties: {
title: 'Mapbox',
description: 'Washington, D.C.'
}
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-122.414, 37.776]
},
properties: {
title: 'Mapbox',
description: 'San Francisco, California'
}
}]
};
// // geocode the typed-in address, zoom to the location, and put a pin on address
// function codeAddress() {
// sAddress = document.getElementById('inputTextAddress').value;
// geocoder.geocode( { 'address': sAddress}, function(results, status) {
// //latitude = results[0].geometry.location.lat();
// //longitude = results[0].geometry.location.lng();
// coordinate = results[0].geometry.location;
// if (status == google.maps.GeocoderStatus.OK) {
// if (GeocodeMarker){
// GeocodeMarker.setMap(null);
// }
// // bounds.extend(results[0].geometry.location);
// // PuppyMap.fitBounds(bounds);
// PuppyMap.setCenter(results[0].geometry.location);
// PuppyMap.setZoom(14);
// GeocodeMarker = new google.maps.Marker({
// map:PuppyMap,
// position: results[0].geometry.location,
// animation: google.maps.Animation.DROP,
// icon: housePin,
// zoom: 0
// });
// }
// else{
// alert("Geocode was not successful for the following reason: " + status);
// }
// });
// }
var marker = new mapboxgl.Marker(document.createElement('div'))
.setLngLat( [-95.925, 29.575])
.addTo(map);
// // add markers to map
// geojson.features.forEach(function(marker) {
// // create a HTML element for each feature
// var el = document.createElement('div');
// el.className = 'marker';
// // make a marker for each feature and add to the map
// new mapboxgl.Marker(el)
// .setLngLat(marker.geometry.coordinates)
// .addTo(map);
// });
</script>

Adding driving time in distance calculation

I'm using this code as a starting point but it only calculates the driving distance between two places and not the driving time.
What would I need to add to the js to get the driving time as well?
I have, btw, already looked at Google Developer's Guide but haven't been able to figure it out.
https://codepen.io/youfoundron/pen/GIlvp
JS:
$(function() {
function calculateDistance(origin, destination) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
$('#result').html(err);
} else {
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
$('#result').html("Better get on a plane. There are no roads between "
+ origin + " and " + destination);
} else {
var distance = response.rows[0].elements[0].distance;
var distance_value = distance.value;
var distance_text = distance.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + " to drive.");
}
}
}
$('#distance_form').submit(function(e){
event.preventDefault();
var origin = $('#origin').val();
var destination = $('#destination').val();
var distance_text = calculateDistance(origin, destination);
});
});
Per the documentation the response element that you get the distance from also includes the duration:
duration
Type: Duration
The duration for this origin-destination pairing. This property may be undefined as the duration may be unknown.
That property has the following properties:
Properties
text
Type: string
A string representation of the duration value.
value
Type: number
The duration in seconds.
Add the version you like to the callback function (probably want text):
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
$('#result').html(err);
} else {
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
$('#result').html("Better get on a plane. There are no roads between "
+ origin + " and " + destination);
} else {
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_value = distance.value;
var distance_text = distance.text;
var duration_value = duration.value;
var duration_text = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + duration_text + " to drive.");
}
}
}
proof of concept fiddle
You are missing the duration.text in the DistanceMatrixResponse' Object so change your else block from:
else {
var distance = response.rows[0].elements[0].distance;
var distance_value = distance.value;
var distance_text = distance.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + " to drive.");
}
To:
else {
var distance = response.rows[0].elements[0].distance;
var distance_value = distance.value;
var distance_text = distance.text;
// Add a variable here to store the duration
var duration_time = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + duration_time " to drive.");
}
duration.text must be added to the ResponseObject as:
result[0].duration.text

Cordova: HTML5 geolocation - find the nearest place from JavaScript array

I have array of places in JavaScript. I need to get gps geolocation from gps sensor (on mobile phone using Apache Cordova).
If GPS accuracy is better than for example 40 meters, I need to do something (set css display:block, change color, ...).
I have this code:
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/distance.js"></script> <!-- https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js -->
<script type="text/javascript" charset="utf-8">
var interval = 5; // [s]
var timeout = 60; // [s]
/* --------------------------------------------------- */
var latitude = new Array();
var longtitude = new Array();
var nameOfLocation = new Array();
// address 1
// Latitude : 10.20 | Longitude : 30.40
latitude[0] = 10.20;
longtitude[0] = 30.40;
nameOfLocation[0] = "address 1";
// address 2
// Latitude : 40.30 | Longitude : 20.10
latitude[1] = 40.30;
longtitude[1] = 20.10;
nameOfLocation[1] = "address 2";
// ...
/* --------------------------------------------------- */
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
console.log('in onDeviceReady()');
$(document).ready(function(){
setInterval(function(i) {
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
maximumAge: 0,
timeout: (timeout*1000),
enableHighAccuracy: true }
);
}, (interval*1000))
});
}
// onSuccess Geolocation
function onSuccess(position) {
console.log('in onSuccess()');
console.log(position.coords.latitude, "position.coords.latitude");
console.log(position.coords.longitude, "position.coords.longitude");
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
var place;
var accuracy;
$("#accuracy").html("GPS accuracy " + position.coords.accuracy + " m.");
if (position.coords.accuracy < 40) {
$("#accuracy").css("background-color", "Gray");
for (var i=0; nameOfLocation.length; i++) {
var distance = getDistance(latitude[0], longitude[0], position.coords.latitude, position.coords.longitude);
if (distance <= 25) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "OrangeRed");
} else if (distance <= 20) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Yellow");
} else if (distance <= 15) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Green");
}
}
$("#info").html("You are about <strong>" + accuracy + "</strong> meters from location <strong>" + nameOfLocation[i] + "</strong>");
} else {
$("#info").html("");
}
}
// onError Callback receives a PositionError object
function onError(error) {
console.log('in onError()');
console.log(error.code, "error.code");
console.log(error.message, "error.message");
$("#geolocation").html(
'code: ' + error.code + '<br />' +
'message: ' + error.message);
$("#accuracy").css("background-color", "");
}
</script>
</head><body>
<p id="info"></p>
<hr />
<p id="accuracy"></p>
<hr />
<p id="geolocation">GPS ...</p>
</body></html>
I use this JS lib for distance measurement of two GPS locations https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js
I can't use google online gps distance lib. App must work without internet connection.
If I run app it start location gps. After first finding location any next finding take only about 5 seconds and after that stop finding locations (this repeats to infinity). I need permanent searching.
Do you know where is an error?
I'm going to do it well?

Phonegap/AngularJS: Get lat/long from inside function

I am trying to set a couple of global variables from inside a function so that I can use the results in an Angular Ctrl.
I have tried everything I can think of and can't seem to get the variable outside of the function. I know this is probably something simple but just can't figure it out!
Thanks in advance for your help.
onSuccess = function(position) {
lat = position.coords.latitude;
lon = position.coords.latitude;
// alert('Latitude: ' + position.coords.latitude + '\n' +
// 'Longitude: ' + position.coords.longitude + '\n' +
// 'Altitude: ' + position.coords.altitude + '\n' +
// 'Accuracy: ' + position.coords.accuracy + '\n' +
// 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
// 'Heading: ' + position.coords.heading + '\n' +
// 'Speed: ' + position.coords.speed + '\n' +
// 'Timestamp: ' + new Date(position.timestamp) + '\n');
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
// ??????
console.log(getCurrentPosition.lat);
EDIT: This is the controller
I need to get lat and lon in place of the current hard coded versions:
var app = angular.module('presto-map', ["ngResource", "ngSanitize", "google-maps"]);
function mapCtrl ($scope) {
// Initialise the map
$scope.map = {
center: {
latitude: 53.58684546368308,
longitude: -1.5543620512747744
},
zoom: 8
};
}
Pass $window to your controller and set lat lng in your scope.
$scope.getCurrentLocation = function () {
$window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.latitude = position.coords.latitude;
$scope.longitude = position.coords.longitude;
$scope.accuracy = position.coords.accuracy;
});
}, function(error) {
alert(error);
});
}
Else if you want to have some global variables in your app use Services to do so. In Service have all the global data and then access it in your controller by passing the service to controllers.
If you are trying to rich lat variable in console.log, then the problem is that your console.log is called before onSuccess handler.
Update:
var app = angular.module('presto-map', ["ngResource", "ngSanitize", "google-maps"]);
function mapCtrl ($scope, $q, $window) {
function getPosition() {
var deferred = $q.defer();
$window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
deferred.resolve({
latitude : latitude,
longitude : longitude,
accuracy : accuracy
});
})
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
// Initialise the map
getPosition().then(function(result) {
$scope.map = {
center: {
latitude: result.latitude,
longitude: result.longitude
},
zoom: 8
};
});
}

Javascript store locator, Uncaught ReferenceError: ... is not defined

I have set an onclick with a variable on a link that calls the calcRoute function for Google maps, and everytime I click the link it says the following Uncaught ReferenceError: NE461UL is not defined The parameter is a postcode by the way.
I have been trying for a while and I can't figure out why it is showing an error.
I have a jquery file with the following line
var distLink = "<a onclick=\"calcRoute(" + postcode + "); return false;\" datalat=" + lat + " datalng=" + lng + " id=\"get-directions\" class=\"directions" + letter +"\">Directions<\/a>";
The calcRoute is in my header
function calcRoute(postcode) {
console.log(marker);
var start = document.getElementById("address").value;
var end = document.getElementById("get-directions").name;
$('get-directions').click(function(){
console.log('click!');
});
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
console.log(JSON.stringify(request));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
postcode must be passed as a string (extra pair of quotation marks around it):
distLink = "<a onclick=\"calcRoute('" + postcode + "'); return false;\" datalat=" + lat + " datalng=" + lng + " id=\"get-directions\" class=\"directions" + letter +"\">Directions<\/a>";

Categories

Resources