0

I have a script which on button click finds the closest location to you by searching an array, it then finds the corresponding entry in another array and adds a number to that array. However I am having issues with appending the value to it. Instead of starting with "0" and then adding 1 making it "1" it comes up like this "01" I thought it was because it was a string to I tried to parse it as an Int this didn't work. I think it may be a problem with the way I am initially setting values in the array, I made a For loop to set the first 200 values to 0, though I only want this to run once then as the button is clicked it appends the number that is typed in to a text field. I am unsure on how to progress with this issue. Code below:

I have tried to highlight the important bits of my code where I think the problem lies.

Screenshot of problem (rather than adding the value I put in the box it just attaches it to the end as if it were a string):

jQuery(function($){



    var Loc1;
    var Loc2;
    var service;
    var marker = [];
    var pos;
    var infowindow;
    var placeLoc
    **var j;**
    **var markerValue  =  [];**

            **for (j = 0; j<200; j++ ){

        markerValue[j] = 0;


    }**

    var markers;

    var x = 0, y = 0,
        vx = 0, vy = 0,
        ax = 0, ay = 0;

    var points;


    var sphere = document.getElementById("sphere");
    var counting = false;
    var counter = 0;
    var numberOne;

if (window.DeviceMotionEvent != undefined) {
    window.ondevicemotion = function(e) {

        ax = event.accelerationIncludingGravity.x * 5;
        ay = event.accelerationIncludingGravity.y * 5;

        document.getElementById("counterSpan").innerHTML = Math.round(counter*10)/10;
        //document.getElementById("accelerationX").innerHTML = Math.round(e.accelerationIncludingGravity.x * 10)/10;
        //document.getElementById("accelerationY").innerHTML = Math.round(e.accelerationIncludingGravity.y * 10)/10;
        //document.getElementById("accelerationZ").innerHTML = Math.round(e.accelerationIncludingGravity.z * 10)/10;

        var moveX = Math.round(e.accelerationIncludingGravity.x * 10)/10;
        //var moveY = Math.round(e.accelerationIncludingGravity.y * 10)/10;
        //var moveZ = Math.round(e.accelerationIncludingGravity.z * 10)/10;

        if(moveX > 5 || moveX < -5) {
            counting = true;
            //alert(counting);
            if(counter < 100){counter+=0.01;}
            }




        if ( e.rotationRate ) {
            //document.getElementById("rotationAlpha").innerHTML = Math.round(e.rotationRate.alpha * 10)/10;
            //document.getElementById("rotationBeta").innerHTML = Math.round(e.rotationRate.beta * 10)/10;
            //document.getElementById("rotationGamma").innerHTML = Math.round(e.rotationRate.gamma * 10)/10;
        }       
    }



    setInterval( function() {
        var landscapeOrientation = window.innerWidth/window.innerHeight > 1;
        if ( landscapeOrientation) {
            vx = vx + ay;
            vy = vy + ax;
        } else {
            vy = vy - ay;
            vx = vx + ax;
        }
        vx = vx * 0.98;
        vy = vy * 0.98;
        y = parseInt(y + vy / 50);
        x = parseInt(x + vx / 50);

        boundingBoxCheck();

        //sphere.style.top = y + "px";
        //sphere.style.left = x + "px";

    }, 25);
} 


function boundingBoxCheck(){
    if (x<0) { x = 0; vx = -vx; }
    if (y<0) { y = 0; vy = -vy; }
    if (x>document.documentElement.clientWidth-20) { x = document.documentElement.clientWidth-20; vx = -vx; }
    if (y>document.documentElement.clientHeight-20) { y = document.documentElement.clientHeight-20; vy = -vy; }

}

function minmax(value, min, max) 
{
    if(parseInt(value) < 0 || isNaN(value)) 
        return 0; 
    else if(parseInt(value) > 100) 
        return 100; 
    else return value;

}



  var $overlay = $('.overlay'),
      resize = true,
      map;



function initialize() {
  /*var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

}*/
var mapOptions = {
    zoom: 15
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Try HTML5 geolocation
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {

            var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

        var request = {
      location:pos,
      center:pos,
      radius:1000,

  };

  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request,callback);
      pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);


        infowindow = new google.maps.InfoWindow({
        map: map,
        position: pos,
        content: 'You Are Here'
      });
        $('#btnEnergize').data('pos',pos);

      map.setCenter(pos);
    }, function() {
      handleNoGeolocation(true);
    });
  } else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
  }



  function callback(results, status) {
      markers = [];
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      markers.push(createMarker(results[i]));
    }
  }
  $('#btnEnergize').data('markers',markers);
}
}



function createMarker(place) {


    placeLoc = place.geometry.location;

  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 8,
        fillColor:'00a14b',
        fillOpacity:0.3,
        fillStroke: '00a14b',       
        strokeWeight:4,
        strokeOpacity: 0.7
    },




  });


  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
  return marker;
}



function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: The Geolocation service failed.';
  } else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
  }

  var options = {
    map: map,
    position: new google.maps.LatLng(60, 105),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}

google.maps.event.addDomListener(window, 'load', initialize);

$('#show').click(function(){

    $overlay.show();

  if ( resize ){
    google.maps.event.trigger(map, 'resize');
    resize = false;
  }

});

$('.overlay-bg').click(function(){

    $overlay.hide();

});


**$( "#btnEnergize" ).click(function() {



    var pos = $(this).data('pos'),
      markers = $(this).data('markers'),
      closest;

      if(!pos || !markers){
    return;
  } 

  $.each(markers,function(){
    var distance=google.maps.geometry.spherical
                  .computeDistanceBetween(this.getPosition(),pos);
    if(!closest || closest.distance > distance){
      closest={marker:this,
               distance:distance}
    }
  });

    if(closest){
    //closest.marker will be the nearest marker, do something with it
    //here we simply trigger a click, which will open the InfoWindow 
    google.maps.event.trigger(closest.marker,'click')


     Loc2 =  closest.marker.getPosition();
     numberOne = $("#numberOne").val();
     alert(numberOne);
     localStorage.setItem('points',numberOne);

     for (var i=0; i<markers.length; i++) {
         Loc1 = markers[i].getPosition();

        if (Loc1.equals(Loc2) /*&& numberOne <= counter*/){


            console.log("marker array Location 1 " + Loc1 + " marker " + i);
            console.log("closest Location 2 " +Loc2);

            counter -= numberOne;
            markerValue[i] += numberOne;


            console.log( "marker " + i + " now equals " + markerValue[i]);

        }
     }
    } 

alert (markerValue[19]);

});**


});// JavaScript Document
1
  • Hey Dan, I would really like to help you but I think, you simply posted way too much code. Could you please simply extract the parts, where your "magic" happens and only post those? Most of your functions don't seem to be relevant to the problem :) Commented Feb 14, 2014 at 16:29

1 Answer 1

1

From skimming over the code it looks like you are retrieving the value here:

numberOne = $("#numberOne").val();

that should be

numberOne = parseInt($("#numberOne").val());

You use parseInt in the function minmax(), but that one is not in use. If this was the one you used to parse the value to int it has one flaw in that it will only return parsed value on 0 and 100:

function minmax(value, min, max) 
{
    // Flip these two, CHECK FOR isNaN first.
    if(parseInt(value) < 0 || isNaN(value)) 
        return 0; 
    else if(parseInt(value) > 100) 
        return 100; 
    else return value; // Here you return value, not parseInt(value)
}
Sign up to request clarification or add additional context in comments.

4 Comments

That function is meant to only allow you to enter a number between 0 and 100 (part of the app) I will try the first suggestion you put and get back to you
seems as though your answer worked, parsing the int as the value is retrieved.
Good. I also had another quick look at the code. I cleaned it up a bit and added some comments on stray variables. It does not look like it, but you are perhaps assuming some variables are global when they are not. There is also the case of unused things, like first infowindow in initialize(). You can have a look at it here.
Thanks for the cleanup, I will try and take in to account some of the changes although some of it is necessary with other elements of my page but I definitely appreciate the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.