I use the googleMaps API to get location data from a given address:
function geocodeAddress(address, callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: address }, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results.length > 0) {
callback(results[0].geometry.location);
} else {
console.log("No results found");
}
} else {
console.log("Geocoder failed due to: " + status);
}
});
}
function getLatLng(address, callback) {
latLng = [];
geocodeAddress(address, function(position) {
latLng.push(position.lat());
latLng.push(position.lng());
callback(latLng);
});
}
// Search for address provided by user via Google Maps API
setMapToSearchAddress: function() {
var vm = this;
// Set the location in map to the address given
setMapLocationToAddress(this.searchAddress);
getLatLng(this.searchAddress, function(latlng) {
console.log(latlng);
vm.latitude = latlng[0];
vm.longitude = latlng[1];
})
}
But when I send a POST request to my server and print the output of the request being sent, I see, that the longitude is sent as a number, whereas the latitude is sent as a string. But I never converted the data?
function postDataToServer(endpoint, data, callback) {
$.post("v1/".concat(endpoint), function(data, response) {
callback(response);
})
}
createIncident: function() {
var incidentData = {
"incidentReference": "",
"latitude": this.latitude,
"longitude": this.longitude,
"streetName": this.address,
"featureTypeId": 1,
"archived": 0
}
console.log(incidentData);
// POST data to server
postDataToServer("incidents", incidentData, function(response) {
console.log(response);
})
},
Object {incidentReference: "", latitude: "48.15312", longitude:
11.583509999999933, streetName: "Leopoldstraße 8", featureTypeId: 1…}archived: 0featureTypeId: 1incidentReference: ""latitude:
"48.15312"longitude: 11.583509999999933streetName: "Leopoldstraße 8"
Why are these variables treated differently?
Related
Here's my issue... I have two selections for my user, use current location, or use a zip code. When the user selects a zip code I make a call to the Google geocode API and retrieve the central point for that zip code. I want to be able to put these coordinates into my Vue model and then execute a method within Vue called refresh which retrieves some data from my database and calls a function that sets up the map with markers and bounds. Since the callback function is decoupled from the model, I cannot seem to set the Vue properties, nor can I call the method. How do I handle the callback?
Please note that the refresh method works properly when using the selection for current location.
getLocation is called when the user selects "Current Location"
checkZip is called when the user selects "Use Zip Code"
<script>
var app = new Vue({
el: '#app-content',
data: {
locationType: "CurrentLocation",
lat: "",
lng: "",
radiusInMiles: 10,
filters: [],
zipCode: "",
geoError: "",
error: "",
results: []
},
methods: {
getLocation: function () {
this.zipCode = "";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.storeLocation, this.locationError);
} else {
this.locationType = "ZipLocation";
console.log("Geolocation does not appear to be supported by the browser.");
this.geoError = "Unable to obtain location. Please make sure location services are turned on and try again.";
}
},
storeLocation: function (position) {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.refresh();
},
locationError: function (err) {
this.locationType = "ZipLocation";
this.results = [];
console.warn(err);
this.geoError = "Unable to obtain location. Please make sure location services are turned on and try again.";
},
refresh: function () {
if (!(this.lat && this.lng && this.radiusInMiles && this.filters)) {
console.log("Location and filters are undefined.");
}
else {
//https://github.com/axios/axios
axios
.post('xyxyxyxyx', {
lat: this.lat,
lng: this.lng,
radiusInMiles: this.radiusInMiles,
filters: this.filters.toString()
})
.then(response => {
this.results = response.data.d;
//Send to map function...
loadMap(this.lat, this.lng, this.results);
})
.catch (error => console.log(error))
}
},
checkZip: function () {
if (this.zipCode.length == 5 && !isNaN(this.zipCode)) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'zipcode ' + this.zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Here's my issue...
//How do I store to the model and then call this.refresh
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng();
this.refresh();
} else {
console.error("Request failed.")
}
});
}
}
}
})
</script>
I was able to get this to work by copying the Vue model into a variable (self).
How can I update a Vue app's or component's property in a promise call back?
checkZip: function () {
if (this.zipCode.length == 5 && !isNaN(this.zipCode)) {
var self = this;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'zipcode ' + this.zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.lat = results[0].geometry.location.lat();
self.lng = results[0].geometry.location.lng();
self.refresh();
} else {
console.error("Request failed.")
}
});
}
}
I want to display console data on my localhost whenever a button is clicked. How would I display such data on my website? When I click the button, I see the data in the console and all I need now is for the actual data to be visualized in a grid view or similar.
I'm rather new to this, hence why I'm here.
function ipLookUp () {
$.ajax('http://ip-api.com/json')
.then(
function success(response) {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country', response.country);
getAddress(response.lat, response.lon)
},
function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
function getAddress (latitude, longitude) {
// $.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=AIzaSyAq3EWvKjpBxwlovWzvnH5xj9zXVk9_C10')
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' +longitude + '&key=AIzaSyAq3EWvKjpBxwlovWzvnH5xj9zXVk9_C10')
.then(
function success (response) {
console.log('User\'s Address Data is ', response)
},
function fail (status) {
console.log('Request failed. Returned status of',
status)
}
)
}
if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log('latitude', position.coords.latitude,
'longitude', position.coords.longitude);
getAddress(position.coords.latitude,
position.coords.longitude)
},
function error(error_message) {
// for when getting location results in an error
console.error('An error has occured while retrieving location', error_message)
ipLookUp()
});
}
else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
ipLookUp()
}
The output in the console looks like this:
{status: "success", country: "Sweden", countryCode: "SE", region: "E", regionName: "Östergötland", …}
as: "AS205016 HERN Labs AB"
city: "Linköping"
country: "Sweden"
countryCode: "SE"
isp: "HERN Labs AB"
lat: 58.4116
lon: 15.6268
org: ""
query: "77.111.247.148"
region: "E"
regionName: "Östergötland"
status: "success"
timezone: "Europe/Stockholm"
zip: "582 22"
Try to create HTML elements and define IDs for easier access through selectors (getElementById for example).
<html>
<body>
<p id="coords"></p>
<p id="country"></p>
<p id="address"></p>
</body>
</html>
Then you can access the element and update it:
function getAddress (latitude, longitude) {
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' +longitude + '&key=KEY')
.then(
function success (response) {
document.getElementById('address').innerHTML = 'User\'s Address Data is ' + response;
},
function fail (status) {
console.log('Request failed. Returned status of',
status)
}
)
}
Hopes this helps you ! you can read more about Javascript from MDN
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body onload="fetchCurrentLocation()">
<div id="list"></div>
<script>
function renderList(response) {
let ul = document.createElement('ul');
if (response.status === "OK ") {
let list = response.results;
for (let index = 0; index < list.length; index++) {
let item = list[index];
let li = document.createElement('li');
li.innerHTML = `<span> ${item.formatted_address} </span>`;
ul.appendChild(li);
}
} else {
let li = document.createElement('li');
li.innerHTML = `<span> Something goes wrong </span>`;
ul.appendChild(li);
}
document.getElementById('list').appendChild(ul);
}
function ipLookUp(params) {
$.ajax('http://ip-api.com/json')
.then(
function success(response) {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country', response.country);
getAddress(response.lat, response.lon)
},
function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
function getAddress(latitude, longitude) {
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&key=AIzaSyAq3EWvKjpBxwlovWzvnH5xj9zXVk9_C10')
.then(
function success(response) {
console.log('User\'s Address Data is ', response)
renderList(response);
},
function fail(status) {
renderList(response);
console.log('Request failed. Returned status of', status)
}
)
}
function fetchCurrentLocation() {
if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log('latitude', position.coords.latitude,
'longitude', position.coords.longitude);
getAddress(position.coords.latitude,
position.coords.longitude)
},
function error(error_message) {
// for when getting location results in an error
console.error('An error has occured while retrieving location', error_message)
ipLookUp()
});
}
else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
ipLookUp()
}
}
</script>
</body>
</html>
I try to do a map with seach address/find location and take gps coordinate/find location. I can make to work one by one but I couldn't work them together in one map. These are my google map functions :
Address Search
// When the search form is submitted
jQuery('.js-form-search').on('submit', function(){
GMaps.geocode({
address: jQuery('.js-search-address').val().trim(),
callback: function ($results, $status) {
if (($status === 'OK') && $results) {
var $latlng = $results[0].geometry.location;
$mapSearch.removeMarkers();
$mapSearch.addMarker({ lat: $latlng.lat(), lng: $latlng.lng(), title: 'Adres : '+jQuery('.js-search-address').val()});
$mapSearch.fitBounds($results[0].geometry.viewport);
document.getElementById("lat").value = $latlng.lat();
document.getElementById("long").value = $latlng.lng();
} else {
alert('Adres Bilgisi Bulunamadı ! ');
}
}
});
return false;
});
GPS Location finder
// When the GPS button clicked
jQuery('.js-form-gps').on('submit', function(){
GMaps.geolocate({
success: function(position) {
$mapSearch.setCenter(position.coords.latitude, position.coords.longitude);
$mapSearch.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
animation: google.maps.Animation.DROP,
title: 'GeoLocation',
infoWindow: {
content: '<div class="text-success"><i class="fa fa-map-marker"></i> <strong>Your location!</strong></div>'
}
});
},
error: function(error) {
alert('Geolocation failed: ' + error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
},
always: function() {
// Message when geolocation succeed
}
});
return false;
});
};
How can I entegrate two of them ?
Thanks,
I want to find the location name which user select on map.
Currently I am getting latitude and longitude both.
But unable to get the location name.
I am using angularJS and angular-google-maps 2.1.5.
Here is the html.
<ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="true" options="options" events="map.events">
</ui-gmap-google-map>
JS :
$scope.map = {
center: {
latitude: 21.0000,
longitude: 78.0000
},
zoom: 4,
events: {
click: function(mapModel, eventName, originalEventArgs,ok) {
var e = originalEventArgs[0];
objOneDevice.dev_latitude = e.latLng.lat();
objOneDevice.dev_longitude = e.latLng.lng();
$scope.templatedInfoWindow.show = true;
}
}
};
$scope.options = {
scrollwheel: true
};
Anything is appreciated.
Here what I have done using Reverse geocoding.
$scope.map = {
center: {
latitude: 21.0000,
longitude: 78.0000
},
zoom: 4,
events: {
click: function(mapModel, eventName, originalEventArgs,ok) {
var e = originalEventArgs[0];
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
console.log(results[1].formatted_address); // details address
} else {
console.log('Location not found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}
}
};
Given Latitude/Longitude object you can map location to approximate address using Google Map API.
You can use the Geocoding API for mapping locations to addresses and addresses to locations.
Geocoder.geocode( { 'latLng': latLngObject }, callbackFn);
Here is the link for Google Map API for Geocoding.
Try these links
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse?csw=1
Use the Geocoding API for mapping locations to addresses and addresses to locations. http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
Geocoder.geocode( { 'latLng': latLngObject }, callback);
http://wbyoko.co/angularjs/angularjs-google-maps-components.html
Hope it helps!!!
I'm trying to order a bunch of coordinates by their distance to another input coordinate. Whenever I try to order, I get the error code 500. Any ideas?
Here's an image of the response codes and I circled the error code associated with my GET request.
Here's the Javascript in the Django template:
function searchWaypoints() {
geocoder.geocode({
'address': $('#address').val()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
$.get("{% url 'waypoints-search' %}", {
lat: position.lat(),
lng: position.lng()
}, function (data) {
if (data.isOk) {
$('#waypoints').html(data.content);
waypointByID = data.waypointByID;
activateWaypoints();
} else {
alert(data.message);
}
}, 'json');
} else {
alert('Could not find geocoordinates for the following reason: ' + status);
}
});
}
$('#searchWaypoints').click(searchWaypoints);
$('#address').keydown(function(e) {
if (e.keyCode == 13) searchWaypoints();
});
Here's the urls.py"
urlpatterns = patterns('waypoints.views',
url(r'^$', 'index', name='waypoints-index'),
url(r'^save$', 'save', name='waypoints-save'),
url(r'^search$', 'search', name='waypoints-search'),
)
Here's the view in views.py:
def search(request):
'Search waypoints'
# Build searchPoint
try:
searchPoint = Point(float(request.GET.get('lng')), float(request.GET.get('lat')))
except:
return HttpResponse(simplejson.dumps(dict(isOk=0, message='Could not parse search point')))
# Search database
waypoints = Waypoint.objects.distance(searchPoint).order_by('distance')
# Return
return HttpResponse(simplejson.dumps(dict(
isOk=1,
content=render_to_string('waypoints/waypoints.html', {
'waypoints': waypoints
}),
waypointByID=dict((x.id, {
'name': x.name,
'lat': x.geometry.y,
'lng': x.geometry.x,
}) for x in waypoints),
)), mimetype='application/json')
Change mimetype='application/json' to content_type="application/json"
or you can just use JsonResponse in Django
https://docs.djangoproject.com/en/1.8/ref/request-response/#jsonresponse-objects