I have a simple page which makes two JQuery AJAX calls to get parameters and then it updates a google maps Lat and Lng,
For some reason after the two AJAX calls are made, the google map then seems to timeout and go Grey.
Anyone ever experienced this before or have any ideas as of why it would be doing this?
Thanks
var pclat;
var pclng;
var pc = document.forms[0]["postcode"].value;
$.get("get_latlong.php", { cp: pc, cord: "Lat" }, function(data){
alert("Lat: " + data);
pclat = data;
});
$.get("get_latlong.php", { cp: pc, cord: "Lng" }, function(data){
alert("Long: " + data);
pclng = data;
});
updateMap(pclat, pclng);
}
function updateMap(pclat, pclng){
var postcodeLL = new google.maps.LatLng(pclat, pclng);
map.panTo(postcodeLL);
marker.setPosition(postcodeLL);
marker.setMap(map);
}
Related
I want to get the the users current location address(city, street etc) on click event.
I have tried html5 geolocation and tried to console the data. on button click i am checking geo location is supported by creating alert box, and its executes succesfully, But its not printing any values in the console.
HTML
<div id="navbar"><span> Geolocation API</span></div>
<div id="wrapper">
<button id="location-button">Get User Location</button>
<div id="output"></div>
My script
<script>
$('#location-button').click(function(){
if (navigator.geolocation) {
alert("it is supported");
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
$.get( "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude +"&sensor=false", function(data) {
console.log(data);
})
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=13&size=800x400&sensor=false";
$('#output').html(img);
});
}
else
{
console.log("geo location is not supported")
}
});
</script>
I want to get the full address of the users location.
You may visit this jsfiddle sample that demonstrates your use case.
Kindly note that it is not recommended to use web service in the client side, as web service requests are recommended to be used for server side requests.
As you can see below, what I used is a Geocoder Service instead of the Web Service Geocoding
geocoder.geocode( { 'location': pos}, function(results, status, infowindow) {
if (status == 'OK') {
console.log(results[0].formatted_address);
infoWindow.setContent('Location found: '+ results[0].formatted_address);
infoWindow.setPosition(pos);
infoWindow.open(map);
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
you simply can't! Geolocation use triangulation or GPS from the mobile and you'll get get longitude and latitude values or even the IP and you'll get nearest distributor device(haven't right word in english).
Obviously for geolocation the user have to authorize it too.
So if you want address the simpliest is to ask by a form. You can use a map related with longit/latitude matching but it'll be a pain and waste to do because you've to use all maps and places on earth related to use it that way.
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.
Here the code.
1.code from template-maps.php:
var pos;
var posZae = function(pos){
return {
coords: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
accuracy: pos.coords.accuracy.toFixed()
},
timestamp: pos.timestamp
}
};
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
var netPOS = JSON.stringify(posZae(position));
$.ajax({
type: 'POST',
data: { 'pos' : pos},
url: '/wp-content/themes/honolulu/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
it should send the data to template-userslocation.phpwhere I have this code:
<?php
/**
* Template Name: template-userslocation
*/
$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>
I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.
Solved:
The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.
Here the info
EDIT 2
I have no idea about any WordPress plugins or PHP. Does the lat/lng appear on the network/at the server? Anyway try this: -
var posZae = function(pos){
return {
lat: pos.coords.latitude,
lng: pos.coords.longitude,
}
};
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = posZae(position);
var netPOS = JSON.stringify(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
$.ajax({
type: 'POST',
data: { 'pos' : netPos},
url: '/wp-content/themes/honolulu/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
EDIT 1
OK would this ring any bells of familiarity with you?
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
var netPOS = JSON.stringify(pos4Net(position));
$.ajax({
type: 'POST',
data: { 'pos' : netPOS},
url: '/wp-content/themes/atripby/template-userslocation.php'
});
ORIGINAL POST:
Not sure where you "pos" is declared. Maybe localizing it with VAR will help instantiate it?
I've had the same/similar problem with the nature of the position object and call the following before trying to transmit it over the network: -
var pos4Net =
function(pos)
{
return {
coords: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
accuracy: pos.coords.accuracy.toFixed()
},
timestamp: pos.timestamp
}
}
So var yourPos = pos4Net(position)
there is no data. Nothing in the page and in the console.
Your PHP code copies the POSTed data into a couple of variables. That is all.
It doesn't output anything. It doesn't use the variables for anything.
It just stores in the data in variables, then exits (which destroys the variables because they only exist for the lifetime of the program execution).
You need to do something with the data.
You could just output it straight back:
<?php header("Content-Type: text/plain"); echo $lat; echo $lng; ?>
… which isn't very useful, but serves as a demonstration.
Your JavaScript does nothing with the response.
(The response, as mentioned above, doesn't contain anything, so you need to fix the PHP first).
You have no success handler in your JavaScript, so when the browser gets the response, your code doesn't do anything with it. This is why nothing is shown in the browser.
url: '/wp-content/themes/atripby/template-userslocation.php'
}).done(function(data) { console.log(data); });
… would show the results in the browser's developer tools console.
first console your lat. and lang. to check if you get any result then use the following code in ajax
data: { 'lang' : coordinates , 'lat': coordinate},
then use $_POST['lant'] and $_POST['lang'] in destination file
The ajax function is sending pos which is an object but you are using array notation within the php script to access the lat/lng.
Perhaps if you did
$.ajax({
type: 'POST',
data: { lat:pos.lat, lng:pos.lng },
url: '/wp-content/themes/atripby/template-userslocation.php'
});
You could then, in the PHP, try
$lat=!empty( $_POST['lat'] ) ? $_POST['lat'] : null;
$lng=!empty( $_POST['lng'] ) ? $_POST['lng'] : null;
EDIT: Just finished up the project. New link is up here! http://codepen.io/myleschuahiock/full/pyoZge/
I'm in the process of making a Weather Widget App for my Free Code Camp. Everything except the "city" is a static placeholder. I'm using the Open Weather Api, which makes us to a latitude and longitude. For debugging purposes, I placed the longitude and latitude of my area underneath the time placeholder.
My problem is that when I statically input the lat and lon on my API link, it works just fine. It returns "Mandaluyong City", a nearby city where I live:
http://api.openweathermap.org/data/2.5/weather?lat=14.603814400000001&lon=121.04907589999999&id=524901&APPID=ca8c2c7970a09dc296d9b3cfc4d06940
But when I do this, where I dynamically add mylatitude and mylongitude, to complete the API link:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
I always get "Moscow" as my city.
Please take a closer look at my Javascript/JQuery code here!
http://codepen.io/myleschuahiock/pen/zqYzWm?editors=0010
Thank you very much! Much appreciated!
Easy solution for you.
Move the $.getJSON() into your if condition, why attempt to query the weather if the client blocks the location?
As Jaromanda X has pointed out:
navigator.geolocation.getCurrentPosition is asynchronous. So, you're calling $.getJSON before the location is actually determined.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('.geo').html(position.coords.latitude+ " " +position.coords.longitude);
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
});
}else{
$(".geo").html("Please turn on Geolocator on Browser.")
}
});
I hope this helps. Happy coding!
Added
getName(mylatitude, mylongitude);
and changed
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
to
function getName(mylatitude, mylongitude){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
}
http://codepen.io/anon/pen/Yqzvbd?editors=0010
You can use third-party IP API that provides the name of the city. With use jQuery function $.getJSON()
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather';
var APPID = 'APPID';
var ipAPI = 'http://ip-api.com/json/';
$.getJSON(ipAPI).done(function(location) {
$('.geo').html(location.lat + " " + location.lon);
$('.city').html(location.city);
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
APPID: APPID
}).done(function(weather) {
$('#temperature').html(weather.main.temp - 273.15);
})
})
OpenWeatherMap provides the temperature in Kelvin on this I did weather.main.temp - 273.15 to get Celsius
My MVC Controller is getting hit twice on page load, and I am stumped on how to solve this problem.
I'm using navigator.geolocation.getCurrentPosition in my Layout page, and that passes the latitude and longitude to my controller.
I have RenderAction in a div, just in case the user has JavaScript disabled, as some people still do
:-(
This is what is causing my problem:
The RenderAction is getting rendered 1st and hitting the controller. Then, the AJAX request is firing and hitting the controller.
So my controller is getting hit twice per request.
Is there something I'm missing which will stop that, because at the moment, all I can think of is to remove the render action from the page.
Code:
<div class="dvWeather">
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
</div>
if (navigator.geolocation) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var aj = "gl";
$.ajax({
url: '#Url.Action("PvCurrentWeatherConditions", "Weather")',
type: 'get',
data: {
lat: lat,
lon: lon,
aj: aj
},
success: function (result) {
$('.dvWeather').html(result);
}
});
}
public PartialViewResult PvCurrentWeatherConditions(string lat, string lon, string aj)
{
if (Request.IsAjaxRequest())
{
try
{
//TODO create Viewmodel
GeoCoordinate gc = new GeoCoordinate();
var latitude = gc.Latitude = Convert.ToDouble(lat);
var longitude = gc.Longitude = Convert.ToDouble(lon);
string latlon = latitude + "," + longitude;
var displayCurrentConditions = _igcc.CurrentConditions(latlon);
return PartialView("pvCurrentWeatherConditions");
}
catch (FormatException)
{
//TODO get ip address
return PartialView("pvLocationBasedOnIpAddress");
}
catch (Exception)
{
return PartialView("pvError");
}
}
return PartialView("pvLocationBasedOnIpAddress");
}
Perhaps use another method for checking if the visitor has javascript disabled, like noscript:
<noscript>
<meta http-equiv="refresh" content="[URL]?java=off">
</noscript>
then handle the querystring in a new action.
You don't have to remove the Render action. Just make another (negative) check in the div:
<div class="dvWeather">
<script type="text/javascript>
//if (!navigator.geolocation) { : Edit
if (navigator.geolocation == null) {
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
}
</script>
</div>
Edit:
if (navigator.geolocation != null) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
This way only one call will be made.
Hope it helps.
I'm trying to get lng and lat coordinates of the Google Maps API by the next example http://jsbin.com/inepo3/7/edit. I expect a 'success' popup, but it keeps showing the 'Error' popup.
The google maps-request gives the correct json feedback (checked by firebug).
<script type="text/javascript">
$().ready(function() {
$.fn.getCoordinates=function(address){
$.ajax(
{
type : "GET",
url: "http://maps.google.com/maps/api/geocode/json",
dataType: "jsonp",
data: {
address: address,
sensor: "true"
},
success: function(data) {
set = data;
alert(set);
},
error : function() {
alert("Error.");
}
});
};
$().getCoordinates("Amsterdam, Netherlands");
});
</script>
Does anyone know how to fix this issue?
Regards,
Guido Lemmens
EDIT
I found a bether solution using the Google Maps Javascript API combined in jQuery:
<script type="text/javascript">
$().ready(function() {
var user1Location = "Amsterdam, Netherlands";
var geocoder = new google.maps.Geocoder();
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
</script>
Google Map API V3 makes it harder for external libraries to work with JSONP. Here is a blog post about it.
JSONP and Google Maps API Geocoder Plus A Fix w/ jQuery
An alternative way of getting Geocoding is to use the Google Map V3 API Geocoder Service. Here is an example that i helped a person that was having a similar issue as you to replace his JSONP to use Google Map V3 Geocoder Service. Take a look at this JSFiddle Demo:
This is basically the core. We basically use twitter to get the tweet's address (IE. London, Madrid or Georgia etc) and convert the actual address into LatLng using Google Map's Geocoder Service:
$.getJSON(
url1, function(results) { // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});