Search code examples
jqueryangularajaxgoogle-mapsangular10

In Angular 10, drag the marker on the map, put its location inside the model, jQuery does not see the model: my code


In Angular 10 and TypeScript, I want to drag the marker on the map to send the location on the map with jQuery to a method, and in the output I get the address and title of the position and in a model that I have already defined I put it and double-sided that model with the text box in HTML. But it does not recognize the model inside the method and takes the value, but outside the method it takes an unknown value. Please help me. Thank you.

  Html code
    <pre>
        <div class="dialog">
        <div class="modal-header">
       
            <button type="button" class="close" aria-label="Close"   (click)="activeModal.dismiss()">
              <span aria-hidden="true">&times;</span>
            </button>
    
            <h4 class="modal-title" id="modal-basic-title">address form</h4>
        </div>
        <div class="modal-body">
        <div class="card-body map-wrapper">
            <div class="row">
                <div class="col-md-12 input-group map-search">
        <input id="sourceLocation" #sourceLocation="ngModel" (input)="searchLocations()"       name="searchTerm" type="search" [(ngModel)]="searchTerm" class="form-control"  placeholder="  {{searchTitle}}"/>
                    <div class="search-result" style="height: auto">
         <ul *ngIf="searchResult!= undefined && searchResult!=null" class="list-group p-0 m-0">
                    
        <li class="list-group-item" *ngFor="let item of searchResult" (click)="setPlace(item)">
                     <div class="clearfix d-block text-right">
                 <h6 class="float-right m-0 text-primary">{{item.title? item.title: null}}</h6>
                 <h6 class="float-left m-0 text-success">{{item.region? item.region: null}}</h6>
                            </div>
                            <div class="clearfix d-block text-right text-muted">
                                <small>{{item.address? item.address:null}}</small>
                            </div>
                        </li>
                    </ul>
                    </div>
                </div>
                <div id="mapDetails" class="neshan-container"></div>
            </div>
        </div>
    </div>
        <div class="card-footer">
        <form>
            <div class="row form-group">
         <div class="col-md-1"> 
         <label class="label"  for="text-input"> title</label></div>
                <div class="col-md-4">
                    <input type="text"
                    #title="ngModel"
                    [(ngModel)]="showResult.title"
                    name="title"
                    class="form-control input-sm"
                    id="title"
                    maxlength="50" />
                </div>
               <div class="col-md-1">
               <label class="label"  for="text-input">position</label></div>
                <div class="col-md-3">
                    <input type="text"
                    required
                    #lat="ngModel"
                    [(ngModel)]="showResult.lat"
                    name="lat"
                    class="form-control input-sm"
                    id="lat"
                    maxlength="50" />
                    <span *ngIf="!lat.valid" class="errormessage">*</span>
                </div>
                <div class="col-md-3">
                    <input type="text"
                    required
                    #lng="ngModel"
                    [(ngModel)]="showResult.lng"
                    name="lng"
                    class="form-control input-sm"
                    id="lng"
                    maxlength="50" />
                    <span *ngIf="!lng.valid" class="errormessage">*</span>
                </div>
            </div>
            <div class="row form-group">
           
                <div class="col-md-1"><label class="label"  for="text-input">address</label></div>
                <div class="col-md-11">
                    <input type="text"
                    required
                    #address="ngModel"
                    [(ngModel)]="showResult.address"
                    name="address"
                    class="form-control input-sm"
                    id="address"
                    maxlength="150" />
                    <span *ngIf="!address.valid" class="errormessage">*</span>
                </div>
            </div>
    
            <button class="k-button k-primary"  [disabled]="!(lat.valid &lng.valid  && address.valid)" (click)="setLocation()">accept</button>
            <button class="k-button" (click)="activeModal.dismiss()">
                <span aria-hidden="true">close</span>
            </button>
        </form>
        
        </div>
    </div>
    </pre>
    
    
    Ts code
    
    public marker: any;      
    public mymap: any;
    public lat: any
    public lng: any
    public showResultTemp: MapLocation=new MapLocation();
    public showResultTemp1: MapLocation=new MapLocation();
    public showResult: MapLocation=new MapLocation();
    
    ngOnInit(): void {
        this.showResult= new MapLocation(); 
        this.showResultTemp=new MapLocation();
        this.showResultTemp1=new MapLocation();
        this.loadMap();
    }
    
    loadMap(): void {
       
       if(this.mapData != null)
       {
          this.lat=this.mapData.Lat;
          this.lng=this.mapData.Lng;
       }
       else
       {
          this.lat= 36.31329984170837;
          this.lng= 59.56285528431181;
      }
      this.myMap = new L.Map('mapDetails', {
      key: Helpers._webMapKey,
      servicekey: Helpers._serviceMapKey,
      maptype: 'dreamy',
          timeoutReady: 0,
      zoomControl: true,
      center: [this.lat,this.lng],
      searchPlaceholderText: "search",
      zoom: 14,
      activeMarker: true,
      search: true,
      poi: true,
      traffic: true
     });
     this.myMap.setMapType("dreamy");
     this.marker=null;
     this.marker = new L.Marker([this.lat,this.lng],{draggable:true}).addTo(this.myMap);
     
      this.marker.on('drag', this.searchOriginWithLatLng);
      this.marker.on('dragend', this.searchOriginWithLatLng);
     }
    
    searchOriginWithLatLng(event)
    {
        this.showResultTemp= new MapLocation();
        const queryUrl = `https://api.neshan.org/v2/reverse?&lat=${event.target._latlng.lat}&        lng=${event.target._latlng.lng}`;
     let headers = new HttpHeaders().set('Content-Type', 'text')
     .append('Api-Key', Helpers._serviceMapKey);
        const result = ajax({
      method: 'GET',
      url: queryUrl,
      headers: {
        'Api-Key': Helpers._serviceMapKey
      }
      });
      result.subscribe((response:any) => {
      this.changeMarkerDate = response.response;
      this.showResultTemp.title=this.changeMarkerDate.route_name;
      this.showResultTemp.address=this.changeMarkerDate.formatted_address;
      this.showResultTemp.lat=this.lat;
      this.showResultTemp.lng=this.lng;
      this.showResult=  this.showResultTemp;
       });
    
     }

Solution

  •  ngAfterViewInit(): void {
        this.showResult= new MapLocation(); 
        this.marker1.on('dragend', this.searchOriginWithLatLngMarker1);
      }
    
      ngAfterContentInit(): void {
    
      }
    
    
    
    
    searchOriginWithLatLngMarker1(event)
      {
       
        this.showResultTemp= new MapLocation();
        const queryUrl = `https://api.neshan.org/v2/reverse?&lat=${event.target._latlng.lat}&lng=${event.target._latlng.lng}`;
        let headers = new HttpHeaders().set('Content-Type', 'text')
        .append('Api-Key', Helpers._serviceMapKey);
            const result = ajax({
          method: 'GET',
          url: queryUrl,
          headers: {
            'Api-Key': Helpers._serviceMapKey
          }
          });
          result.subscribe((response:any) => {
          this.changeMarkerDate = response.response;
          this.showResultTemp.title=this.changeMarkerDate.route_name;
          this.showResultTemp.address=this.changeMarkerDate.formatted_address;
          this.showResultTemp.lat=event.target._latlng.lat;
          this.showResultTemp.lng=event.target._latlng.lng;
         
          this.showResult=this.showResultTemp;
    
         
          this.showResult.address=this.showResult.address.replace("استان خراسان رضوی،","");
          this.showResult.address=this.showResult.address.replace("مشهد،","");
          this.showResult.address=this.showResult.address.trimStart();
          this.showResult.address=this.showResult.address.trimEnd();
          (document.getElementById("SrcRegion") as HTMLTextAreaElement).value=this.showResult.region;
          (document.getElementById("SrcTitle") as HTMLTextAreaElement).value=this.showResult.title;
          // document.getElementById('SrcAddress').setAttribute("value",this.showResult.address);
          (document.getElementById("SrcAddress") as HTMLTextAreaElement).value=this.showResult.address;
          (document.getElementById("SrcLat") as HTMLTextAreaElement).value=this.showResult.lat;
          (document.getElementById("SrcLng") as HTMLTextAreaElement).value=this.showResult.lng;
    
          event.target.bindPopup(this.showResult.title).openPopup();
    
         const dstlat= (document.getElementById("DstLat") as HTMLTextAreaElement).value 
         const dstlng=(document.getElementById("DstLng") as HTMLTextAreaElement).value
    
          // this.travelModel.SrcLat=this.showResult.lat;
          // this.travelModel.SrcLng=this.showResult.lng;
    
          if(dstlat != undefined && dstlat != null && dstlat!= ""
          && dstlng != undefined && dstlng != null && dstlng!= "")
          {
            this.parameterDirection={
              type: "car",
              origin:  [this.showResult.lat,this.showResult.lng],
              destination:   [dstlat,dstlng],
              avoidTrafficZone: true,
              avoidOddEvenZone: true,
              alternative: true,
          };
    
          const queryUrl2 = `https://api.neshan.org/v3/direction?type=${ this.parameterDirection.type}&origin=${ this.parameterDirection.origin}&destination=${ this.parameterDirection.destination}&avoidTrafficZone=${ this.parameterDirection.avoidTrafficZone}&avoidOddEvenZone=${ this.parameterDirection.avoidOddEvenZone}&alternative=${ this.parameterDirection.alternative}`;
          //const queryUrl = `https://api.neshan.org/v1/search`;
          let headers = new HttpHeaders().set('Content-Type', 'text')
          .append('Api-Key', Helpers._serviceMapKey);
        
    
          const result = ajax({
            method: 'GET',
            url: queryUrl2,
            headers: {
              'Api-Key': Helpers._serviceMapKey
            }
            });
             result.subscribe((response:any) => {
              this.resultDirections=response.response.routes;
              this.resultDirection=this.resultDirections[0];
              //this.travelModel.Distance=Math.round(this.resultDirection.legs[0].distance.value/1000);
              const distance=Math.round(this.resultDirection.legs[0].distance.value/1000);
              document.getElementById('lbldistance').innerHTML= this.resultDirection?.legs[0].distance.text;
              document.getElementById('lbltime').innerHTML= this.resultDirection?.legs[0].duration.text;
              // document.getElementById('Distance').setAttribute("value",distance.toString());
              (document.getElementById("Distance") as HTMLTextAreaElement).value=distance.toString();
              const dateObj = new Date(this.resultDirection.legs[0].duration.value * 1000);
              // this.travelModel.TotalTime={hours:0,minutes:0};
              const h=dateObj.getUTCHours();
              const d=dateObj.getUTCMinutes();
              // this.duration.minutes=dateObj.getUTCHours();
              // this.duration.hours=dateObj.getUTCMinutes();
    
        
              // this.travelModel.TotalTime.hours= h;
              // this.travelModel.TotalTime.minutes= d;
    
              // this.travelModel.FirstServicePrice=(this.station?.InputPrice +(this.station?.KMPrice* this.travelModel.Distance)+(this.station?.DelayPrice* ((h * 60) + d)));
              const inputPrice=(document.getElementById("InputPrice") as HTMLTextAreaElement).value;
              const kmPrice=(document.getElementById("KMPrice") as HTMLTextAreaElement).value;
              const delayPrice=(document.getElementById("DelayPrice") as HTMLTextAreaElement).value;
              //document.getElementById('FirstServicePrice').setAttribute("value",(+inputPrice +(+kmPrice * distance)+(+delayPrice * ((h * 60) + d))).toString());
              const firstPrice=(+inputPrice +(+kmPrice * distance)+(+delayPrice * ((h * 60) + d)));
              (document.getElementById("FirstServicePrice") as HTMLTextAreaElement).value=Helpers.roundNumber(firstPrice).toString();
                      let now = new Date();
                      let hours = ("0" + h).slice(-2);
                      let minutes = ("0" + d).slice(-2);
                      let str = hours + ':' + minutes;
                      this.durectiontime=str;
           
    
                   
                      (document.getElementById("durectiontime") as HTMLTextAreaElement).value=this.durectiontime;
                   
          });
          }
          });
    
      }