I created an HTML button:
...onclick="stLoc();"/>
which gears the stLoc() Javascript function.
My intention is to store the latitude inside the vaulesXarray.
Here's my code:
var valuesX=[];
//This is to show the current position:
function handleLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
valuesX.push(a);
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if (navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
The output I get is an empty array.
Your stLoc() function is expecting pos object to be passed as first parameter.
But in your HTML part of example you're not passing this parameter to function:
<a "onclick="stLoc();">
This causes the error and the application flow breaks.
Update:
button
<script type="text/javascript">
var valuesX=[],
lastPos={a: -1, b: -1};
//This is to show the current position:
function handleLoc(pos) {
// in event handler remember lastPos to use it in stLoc on click.
lastPos.a = pos.coords.latitude;
lastPos.b = pos.coords.longitude;
var p = new L.LatLng(lastPos.a, lastPos.b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc() {
if(lastPos.a != -1) {
valuesX.push(lastPos.a);
}
return false;
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if(navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
</script>
For guys looking out for code to implement this functionality in a different way..
Here is the code
<script language="javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script language="javascript">
function geoSuccess(e){
var lat = e.coords.latitude;
var lon = e.coords.longitude;
var myLoc = "Latitude: " + lat + '<br />Longitude: ' + lon;
$("#mylocation").html(myLoc);
}
function geoFailed(e){
$("#mylocation").html("Failed");
}
window.onload=function(e){
if ( navigator.geolocation){
navigator.geolocation.getCurrentPosition(geoSuccess, geoFailed);
} else {
// Error (Could not get location)
$("#mylocation").html("Failed");
}
}
</script>
<div id="mylocation"></div>
Related
My JavaScript inside the head tag:
<script type="text/javascript">
function over1() {
var img1 = document.getElementById("1").src;
document.getElementById("big").src = img1;
}
function out() {
document.getElementById("big").src = "http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/shop-icon.png";
}
function london() {
var city = document.getElementById("city").value;
var check = city.toLowerCase();
var province = document.getElementById("province").value;
if (check == "london" && province == "ON") {
alert("Visit our company travel store at Masonville Mall!");
}
}
function checkinput() {
var email = document.contest.email.value;
var emailcheck = email.search("#");
if (!document.contest.name.value) {
alert("Enter a name!")
} else {
alert("Thank You " + document.contest.name.value + " " + document.contest.lastname.value + " For Entering The Contest!")
window.open(calculator.html,'_blank');
}
}
</script>
I have the simple JavaScript inside the HTML file, but Chrome won't read it. In Inspector View, it throws ReferenceErrors for all my functions. Please help.
Why do you say that, those are all functions, nothing is invoked from these functions. call the functions and see if they are invoked correctly or not
checkinput();
over1();
/* the rest of them */
I am using Bing map ajax control. In my code i have something as below -
function getMap()
{
map = new Microsoft.Maps.Map(document.getElementById('mnMap'), {
credentials: 'MyKey',
mapTypeId: Microsoft.Maps.MapTypeId.road
});
map.setView({
zoom: 4,
center: new Microsoft.Maps.Location(defaultLat, defaultLan)
});
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', {
callback: createDirectionsManager
});
}
function createDirectionsManager()
{
if (!directionsManager)
{
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
}
directionsManager.resetDirections();
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsPanel') });
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayRouteError );
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayUpdatedRoute );
}
function displayUpdatedRoute(status){
// update waypoint text inputs based on dragged markers
var legs = directionsManager.getAllWaypoints();
// Do some validation
}
function displayRouteError(error){
// If the error is a viapoint error, display an error
if (error.responseCode == Microsoft.Maps.Directions.RouteResponseCode.noSolution){
directionsManager.resetDirections();
}else if (error.responseCode == Microsoft.Maps.Directions.RouteResponseCode.dataSourceNotFound || error.responseCode == Microsoft.Maps.Directions.RouteResponseCode.tooFar){
directionsManager.resetDirections();
}else{
directionsManager.resetDirections();
}
}
function getDirections(submit, send) {
directionsManager.resetDirections();
if (some test condition) {
start = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(locInputs.first().attr("data-lat"), locInputs.first().attr("data-lng")) });
} else {
start = new Microsoft.Maps.Directions.Waypoint({ address: locInputs.first().val() });
}
directionsManager.addWaypoint(start); // waypoint values come from UI based on user input string address
directionsManager.addWaypoint(waypoint);
directionsManager.addWaypoint(end);
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsPanel') });
directionsManager.calculateDirections();
}
function saveTrip(){
var legs = directionsManager.getAllWaypoints();
// do some validations
//ajax call to backend
}
$("#saveTripBtn").click(function() {
getDirections();
saveTrip();
}
getMap() is properly initialized, i can see the directions correctly being displayed. In the waypoints returned by directionsManager.getAllWaypoints(), none of the waypoint has location object inside it - as a result i am not getting lat/long. All i need is lat/long of each waypoint in savetrip() method, before calling the back-end code, which i do not see.
I am using a Developer key as of now. Let me know if i need to provide any more information.
Thanks in advance
Roshan
Use the getLocation method on the Waypoint object to get it's location coordinates: http://msdn.microsoft.com/en-us/library/hh312838.aspx
Here is a working code sample:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map, directionsManager;
function GetMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'YOUR_BING_MAPS_KEY'
});
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', {
callback: getDirections
});
}
function getDirections() {
if (!directionsManager)
{
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
}
directionsManager.resetDirections();
var start = new Microsoft.Maps.Directions.Waypoint({ address: "Seattle, WA" });
var end = new Microsoft.Maps.Directions.Waypoint({ address: "Portland, OR" });
directionsManager.addWaypoint(start);
directionsManager.addWaypoint(end);
directionsManager.calculateDirections();
}
function getWaypoints(){
var wp = directionsManager.getAllWaypoints();
var text = '';
for(var i=0;i<wp.length;i++){
var loc = wp[i].getLocation();
text += 'waypoint ' + i + ': ' + loc.latitude + ', ' + loc.longitude + '\r\n';
}
document.getElementById('output').innerText = text;
}
</script>
</head>
<body onload="GetMap();">
<div id='myMap' style=";width:600px;height:400px;"></div><br/>
<input type="button" onclick="getWaypoints()" value="Get Waypoints" /><br/>
<div id="output"></div>
</body>
</html>
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 retrieve the 2 attributes of seprated function and I debug there values before the end of the function and they have a value but the return value is alwas undifined I don't know why !!
the .js file
function STAAPlanlat(){
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
var lat=position.coords.latitude;
var lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
return lan;
});
} else {
alert("error");
}
}
I got the alert with the values of the lan and lat
but when I call on separated file it return undefined return value
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="STAAP1.2.js"> </script>
<script type="text/javascript">
function test(){
var out=STAAPlanlat();
document.getElementById("STAAPlanlat").value = "lan is"+out;
//document.writeln("lan is"+out);
}
</script>
</head>
<body>
<p id="STAAPlanlat">Test the division</p>
<button onclick="test()">STAAPlanlat()</button>
<button onClick="alertme()" >Alert</button>
</body>
</html>
Cause you're not returning it from the main function, you're returning it from the embedded anonymous function which isn't doing anything with it. Do this:
function STAAPlanlat(){
var lat;
var lan;
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
lat=position.coords.latitude;
lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
});
return lan;
}
else
alert("error");
}
You are returning in the anonymous function and this value is never assigned to anything. You can do what you want with a callback.
// untested code, hope it works
function STAAPlanlat(callback){
alert ("the function");
if (navigator.geolocation) {
navigator.geolocation.watchPosition(function(position) {
var lat=position.coords.latitude;
var lan=position.coords.longitude;
callback(lat, lan);
});
}
else{
alert("error");
}
}
And your test function...
function test(){
var out;
STAAPlanlat(function(lat, lon) { out = lat; });
}
because function STAAPlanlat doesn't return any value. your anonymous function returns lan but it is asynchronous callback.
add this before return lan;:
document.getElementById("STAAPlanlat").value = "lan is" + lan;
This is puzzling me. I'm using Google Map's Geocoding to find locations. I am attempting to use the example here, which is from Google, and it is just not working for me.
Error:
http://maps.gstatic.com/intl/en_us/mapfiles/159e/maps2.api/main.js
Line 174
var point = new GLatLng(,);
Code:
<script src="http://maps.google.com/maps?file=api&v=2&key='.$config['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key='.$config['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script>
<style type="text/css">
#import url("http://www.google.com/uds/css/gsearch.css");
#import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>
<script type="text/javascript">
function addListener(element, baseName, handler) {
if (element.addEventListener)
element.addEventListener(baseName, handler, false);
else if (element.attachEvent)
element.attachEvent("on"+baseName,handler);
}
var map'.$num.';
function initialize'.$num.'()
{
if (GBrowserIsCompatible())
{
map'.$num.' = new GMap2(document.getElementById("google_map'.$num.'"),{mapTypes:[G_HYBRID_MAP]});
var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.');
map'.$num.'.setCenter(new GLatLng('.$row->LocationLat.','.$row->LocationLon.'),4);
var mapControl = new GMapTypeControl();
map'.$num.'.addControl(mapControl);
map'.$num.'.addControl(new GLargeMapControl());
map'.$num.'.addControl(new GOverviewMapControl());
map'.$num.'.enableDoubleClickZoom();
map'.$num.'.enableScrollWheelZoom();
var bounds = new GLatLngBounds;
var myIcon = new GIcon();
myIcon.image = "http://www.google.com/mapfiles/marker.png";
myIcon.iconAnchor = new GPoint((markerImage1.width/2),markerImage1.height);
bounds.extend(point);
setBounds(map'.$num.',bounds);
var address = "' . $address . '";
var geocoder = new GClientGeocoder();
showAddress(address, geocoder);
}
}
function showAddress(address, geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map'.$num.'.setCenter(point, 13);
var marker = new GMarker(point);
map'.$num.'.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
function setBounds(map'.$num.',bounds)
{
map'.$num.'.setZoom(15);
map'.$num.'.setCenter(bounds.getCenter());
}
function chargement()
{
markerImage1 = new Image();
markerImage1.src = "http://www.google.com/mapfiles/marker.png";
setTimeout("initialize'.$num.'()", 500);
}
addListener(window, "load", chargement);
</script>
My code is generated by PHP, so when there is an ' that means I'm opening or closing the string that is holding the JavaScript.
Maybe I didn't get it, but
var point = new GLatLng(,);
is not valid javascript
It should be either
var point = new GLatLng(param1, param2);
or
var point = new GLatLng();
or
var point = new GLatLng(null,null);
... depending on what the GLatLng constructor is
This statement:
var point = new GLatLng(,);
Is not correct because there isn't a lat or lng number specified. This is because this statement:
var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.');
Is incorrect. I'd try something like:
var point = new GLatLng(<?php echo $row->LocationLat . ',' . $row->LocationLon; ?>);
If that doesn't work, then $row->LocationLat or $row->LocationLon are possibly empty.
Problem 1- The function showAddress() is not closed.
Problem 2 - your map object needs to be defined outside of the functions so that showAddress() can access it.
Problem 3 - The references to the map object inside of showAddress() are incorrect
check if the php string you are printing into the html+js exists in the first place. php generates the htm and sends it to the user, for now on it's htm+javascript problem.
it looks like a javascript problem, but you really generated a wrong syntax with php to begin with, because you tried to print something problematic and it printed an empty space.
always be careful of that, be sure of what you print.