简体   繁体   中英

Method inside geocoder.geocode javascript

I want to add a method inside de function of geocoder.geocode, but show me a error like this TypeError: this.updateMarkerPosition is not a function. the method work offside the function but inside not, i don't know why.

here is the code

     var mapa = {
  address : "",
  geocoder : "",
  my_imagen : "",
  iniciarMapa : function(){

    this.geocoder = new google.maps.Geocoder();
    this.my_imagen = './images/edicion.png';  
  latLng = new google.maps.LatLng(-33.02511643971983,-71.54983196508181);
  map = new google.maps.Map(document.getElementById('map1'), {
    zoom:15,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAD  });

// CREACION DEL MARCADOR  
    marker = new google.maps.Marker({
    position: latLng,
    title: 'Arrastra el marcador si quieres moverlo',
    map: map,
    icon: this.my_imagen,
    draggable: true
  });


  },
   updateMarkerPosition : function(latLng) {
      document.form_mapa.longitud.value ="latLng.lng()";
      document.form_mapa.latitud.value = "latLng.lat()";
    },

  codeAddress : function() {
        this.address = document.form_mapa.direccion.value;
        if (this.address == ""){
            alert('Debe ingresar una dirección');
            return;
        }
      else
        {

          var status = this.geocoder.geocode( { 'address': this.address}, function(results, status) {
            this.updateMarkerPosition();

          });
          console.log(status);



        }

      }




}

the callback-function of geocoder.geocode will be executed in global scope, where this will refer to the global window -object and not to mapa

call mapa.updateMarkerPosition(); instead.

When you want to be more flexible and don't want to hardcode the name of the object create a closure that points to the object:

  codeAddress : function() {
     //create reference to the object
     var that = this;

     this.address = document.form_mapa.direccion.value;
        if (this.address == ""){
            alert('Debe ingresar una dirección');
            return;
        }
      else
        {

          var status = this.geocoder.geocode( { 'address': this.address}, function(results, status) {
            //use the reference
            that.updateMarkerPosition();

          });
          console.log(status);
        }
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM