Centering on request, Google Maps adjusts its view to focus on

When I select a row, I want to set the map center to the provided coordinates in Primeng. The issue is that while this.options works fine in ngOnInit, it doesn't work when called in the showCords() function. Below is my code:

gmap.component.ts

import {Component, OnInit} from '@angular/core';
import {Message} from '../message';
import {AppService} from '../app.service';
import {Map} from './map';

declare var google: any;

@Component({
    templateUrl: '/app/gmaps/gmap.component.html'
})

export class GMapComponent implements OnInit {

    options: any;
    selectedCord: Map[];
    map: Map = new PrimeCord();
    overlays: any[];

    dialogVisible: boolean;

    markerTitle: string;

    selectedPosition: any;

    infoWindow: any;
    selMap: boolean;
    draggable: boolean;

    msgs: Message[] = [];

    maps: Map[];

    constructor(private _appService: AppService) { }

    ngOnInit() {
        this.options = {
            center: { lat: 31.531259, lng: 74.352743 },
            zoom: 12
        };

        this.initOverlays();

        this.infoWindow = new google.maps.InfoWindow();
    }

    handleMapClick(event) {
        this.dialogVisible = true;
        this.selectedPosition = event.latLng;
    }

    handleOverlayClick(event) {
        this.msgs = [];
        let isMarker = event.overlay.getTitle != undefined;

        if (isMarker) {
            let title = event.overlay.getTitle();
            this.infoWindow.setContent('<div>' + title + '</div>');
            this.infoWindow.open(event.map, event.overlay);
            event.map.setCenter(event.overlay.getPosition());

            this.msgs.push({ severity: 'info', summary: 'Marker Selected', detail: title });
        }
        else {
            this.msgs.push({ severity: 'info', summary: 'Shape Selected', detail: '' });
        }
    }

    addMarker() {
        this.overlays.push(new google.maps.Marker({
            position: {
                lat: this.selectedPosition.lat(),
                lng: this.selectedPosition.lng()
            },
            title: this.markerTitle,
            draggable: this.draggable
        }));

        this.dialogVisible = false;
    }

    saveMarker(lat: number, lng: number) {
        debugger;
        this._appService.postCords(lat, lng, this.markerTitle).subscribe(
            error => console.log(error)
        );
        this.markerTitle = null;
    }

    handleDragEnd(event) {
        this.msgs = [];
        this.msgs.push({ severity: 'info', summary: 'Marker Dragged', detail: event.overlay.getTitle() });
    }

    initOverlays() {
        this._appService.getCords().subscribe(
            res => this.maps = res
        );

        if (!this.overlays || !this.overlays.length) {
            this.overlays = [
                new google.maps.Marker({ position: { lat: 31.531259, lng: 74.352743 }, title: "Siddiq Trade Centre" }),
                new google.maps.Marker({ position: { lat: 31.506739, lng: 74.384500 }, title: "Home" }),
                new google.maps.Marker({ position: { lat: 31.528251, lng: 74.402332 }, title: "Allama Iqbal International Airport" }),

            ];
        }
    }

    zoomIn(map) {
        map.setZoom(map.getZoom() + 1);
    }

    zoomOut(map) {
        map.setZoom(map.getZoom() - 1);
    }

    clear() {
        this.overlays = [];
    }


    onRowSelect(event) {
        debugger;
        this.selMap = true;
        this.map = this.cloneMap(event.data);

        this.showCords();
    }

    cloneMap(m: Map): Map {
        let map = new PrimeCord();
        for (let prop in m) {
            map[prop] = m[prop];
        }
        return map;
    }

    showCords() {
        this.overlays.push(new google.maps.Marker({
            position: {
                lat: this.map.lat,
                lng: this.map.lng
            },
            title: this.map.title
        }));
        this.options = {
            center: { lat: this.map.lat, lng: this.map.lng },
            zoom: 15
        }
    }
}

class PrimeCord implements Map {
    constructor(public title?, public lat?, public lng?) { }
}

gmap.component.html

<div class="ContentSideSections Implementation">
    <p-growl [value]="msgs"></p-growl>

    <p-gmap #gmap [style]="&#123;'width':'100%','height':'320px'&#125;" [options]="options" [overlays]="overlays"
            (onMapClick)="handleMapClick($event)" (onOverlayClick)="handleOverlayClick($event)" (onOverlayDragEnd)="handleDragEnd($event)"></p-gmap>
    <button type="button" pButton label="Clear" icon="fa-close" (click)="clear()" style="margin-top:10px"></button>
    <button type="button" pButton label="Reset" icon="fa-map-marker" (click)="initOverlays()" style="margin-top:10px"></button>
    <button type="button" pButton label="Zoom In" icon="fa-search-plus" (click)="zoomIn(gmap.getMap())" style="margin-top:10px"></button>
    <button type="button" pButton label="Zoom Out" icon="fa-search-minus" (click)="zoomOut(gmap.getMap())" style="margin-top:10px"></button>
    <p-dialog showEffect="fade" [(visible)]="dialogVisible" header="New Location">
        <div class="ui-grid ui-grid-pad ui-fluid" *ngIf="selectedPosition">
            <div class="ui-grid-row">
                <div class="ui-grid-col-2"><label for="title">Label</label></div>
                <div class="ui-grid-col-10"><input type="text" pInputText id="title" [(ngModel)]="markerTitle"></div>
            </div>
            <div class="ui-grid-row">
                <div class="ui-grid-col-2"><label for="lat">Lat</label></div>
                <div class="ui-grid-col-10"><input id="lat" type="text" readonly pInputText [ngModel]="selectedPosition.lat()" ngDefaultControl></div>
            </div>
            <div class="ui-grid-row">
                <div class="ui-grid-col-2"><label for="lng">Lng</label></div>
                <div class="ui-grid-col-10"><input id="lng" type="text" readonly pInputText [ngModel]="selectedPosition.lng()" ngDefaultControl></div>
            </div>
            <div class="ui-grid-row">
                <div class="ui-grid-col-2"><label for="drg">Drag</label></div>
                <div class="ui-grid-col-10"><p-checkbox [(ngModel)]="draggable" ngDefaultControl></p-checkbox></div>
            </div>
        </div>
        <footer>
            <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
                <button type="button" pButton label="Add Marker" icon="fa-plus" (click)="addMarker(); saveMarker(selectedPosition.lat(), selectedPosition.lng());"></button>
            </div>
        </footer>
    </p-dialog>
</div>
<div *ngIf="selMap">
    <h3>Title: {{map.title}}</h3>
    <h3>Latitude: {{map.lat}}</h3>
    <h3>Longitude: {{map.lng}}</h3>
</div>
<div>
    <p-dataTable [value]="maps" selectionMode="single" [(selection)]="selectedCord" 
                 (onRowSelect)="onRowSelect($event)" 
                 [paginator]="true" rows="15" [responsive]="true">
        <header>Record</header>
        <p-column field="title" header="Title" [sortable]="true"></p-column>
        <p-column field="lat" header="Latitude" [sortable]="true"></p-column>
        <p-column field="lng" header="Longitude" [sortable]="true"></p-column>
    </p-dataTable>
</div>

Answer №1

Check out this code snippet for a map component integration:

<ngx-map #map [style]="&#123;'width':'100%','height':'400px'&#125;" *ngIf="data.center" [options]="data.options" [markers]="data.markers"
        (onMapClick)="handleMapClick($event)" (onMarkerClick)="handleMarkerClick($event)" (onMarkerDragEnd)="handleMarkerDragEnd($event)"></ngx-map>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a URL link to a mentioned user from angular2-mentions within an Angular 4 application can be achieved in the following way:

Need help with adding a URL RouterLink to mention a user using angular2-mentions. This is the code snippet I currently have: <div class="col-sm-12"> <input type="text" [mention]="contactNames" [mentionConfig]="{triggerChar:'@',maxI ...

"Unexpected outcome: Angular's HTTP request for a JSON file yields an undefined

Learning Angular has been a challenging experience for me. I am currently working on reading a json file into a chart on my main app page to visualize temperature data from my PI. Despite trying various methods found online, I have not been successful so f ...

Testing an Angular hybrid application resulted in the error message "Unable to access property 'nativeElement' of null."

I'm encountering a problem with a straightforward test: it ('should be able to navigate to add program', fakeAsync(() => { let href = fixture.debugElement.query(By.css('.add-program-btn')); let link = href.nativeElement.get ...

Exploring Angular: A Comparison of AfterViewInit() and AfterContentInit()

I am trying to understand exactly what triggers the AfterViewInit() and AfterContentInit() life-cycle hooks. According to the Angular documentation, AfterViewInit() is called by Angular after it creates a component's child views. and for AfterCon ...

How to extract a type from a nested type using TypeScript

I am trying to define a type structure where both a and foo are optional: type Something = { a?: { foo?: { bar: { c: { id: string, countryCode: number, animal: { ... } } } } } } Now I n ...

What are the steps to incorporate a type-safe builder using phantom types in TypeScript?

In order to ensure that the .build() method can only be called once all mandatory parameters have been filled, it is important to implement validation within the constructor. ...

Encountering an endless loop within a data rest API in a React application

Currently, I am in the process of learning React and attempting to utilize the Poke API with my application. Unfortunately, I seem to have run into an infinite loop issue and I am feeling quite lost in terms of troubleshooting it. Below is a snippet of my ...

Updating color of an element in SVG and Angular2+ according to the background

In my svg element, I have a text element positioned after two rect elements. <svg id="floor-plan" width="300" height="100"> <rect width="300" height="100" fill="white"/> <rect width="50" height="50" fill="green"/> <text x="10" y="10" ...

The tooltip display in ng2-google-charts is not functioning properly

In my project, I am utilizing the ng2-google-charts library to generate a Timeline chart with a customized tooltip. The requirement is fairly simple - I need to display a specific value based on certain conditions. Below is the relevant code snippet: Comp ...

Troubleshooting: When Angular Fade In Out Animation Won't Work

Looking to create a simple animation with the angular animation package The goal is to smoothly transition from opacity 0 to opacity 1 for a fade effect. I've had success with other properties like height and display, but struggling with opacity. H ...

Defining Multiple Types in Typescript

I have created an interface in a TypeScript definition file named d.ts: declare module myModule { interface IQedModel { field: string | string[]; operator: string; } } In an Angular controller, I have utilized this interface like ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

Learn how to dynamically adjust context using a server-client architecture with TRPC

Currently, I am referring to the tRPC documentation for guidance on creating a server side caller. But I'm facing a challenge in dynamically setting the value when incorporating it into my NextJS 13 pages. In my context.ts file, you will find the fol ...

Issue with Angular Unit Test: Provider for WebSocketAPI is missing

I am encountering some failing unit tests in my Angular 10 application due to the following error message: Failed: R3InjectorError(DynamicTestModule)[WebSocketAPI -> WebSocketAPI]: NullInjectorError: No provider for WebSocketAPI! Typically, this type ...

"Angular application does not have a reference to elementRef after completion of build

I have encountered an issue with my component template. I am trying to select an SVG element using ElementRef and it seems to work fine. However, when I build the app and open it, the elementRef is null. @Component({ selector: 'app-svg&apos ...

Error encountered during installation of Nativescript Post Install Script

While I am comfortable running one of our current projects with Nativescript, I encountered an error when attempting to install it on a new project using the following command: sudo ng new --collection=@nativescript/schematics the-juice-box --shared The ...

What is the method to ensure that the option group is selectable?

Is there a way to enable the selection of an option group? <select> <optgroup value="0" label="Parent Tag"> <option value="1">Child Tag</option> <option value="2">Child Tag</option> </optgroup> ...

Exploring the narrowing capabilities of TypeScript within while loops

When I write while loops, there are times when I know for sure that a certain value exists (connection in this case), but the control flow analysis is unable to narrow it down. Here's an illustration: removeVertex(vertex: string) { const c ...

Encountering compilation issues when transitioning from Angular 7 to Angular 8

Upon upgrading my project to Angular 8, an unexpected error occurs during the build process: ERROR in HostResourceLoader: loader(C:/myapp/cli/src/app/pages/user-home/user-home.component.html) returned a Promise i 「wdm」: Failed to compile. Ho ...

What is the best way to shorten text in Angular 2?

Can the length of a string be limited to a specific number of characters in AngularJS code? For example, if I need to restrict the title length to 20 characters {{ data.title }}. Is there a built-in pipe or filter available to set this character limit? ...