繁体   English   中英

geocoder.geocode javascript内部的方法

[英]Method inside geocoder.geocode javascript

我想在geocoder.geocode的函数内部添加一个方法,但向我显示类似TypeError的错误:this.updateMarkerPosition不是函数。 该方法在功能之外起作用,但在内部不起作用,我不知道为什么。

这是代码

     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);



        }

      }




}

geocoder.geocode的回调函数将在全局范围内执行, this将引用全局window -object而不是mapa

调用mapa.updateMarkerPosition(); 代替。

当您想要更灵活并且不想对对象的名称进行硬编码时,请创建一个指向该对象的闭包:

  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);
        }
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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