Issues with loading AddMarker on initial launch in Ionic 2

Can someone help me figure out what's causing the issue in my code? When I try to load a google map in my ionic 2 app, the marker doesn't show up the first time. It only appears when I reload the map for the second time or later.

I also need assistance on how to display the route between the user's location and the marker's location.

export class Map implements OnInit {

map:GoogleMap;
  constructor(public navCtrl: NavController, public navParams: NavParams,private googleMaps: GoogleMaps) {}

 ngOnInit() {
 this.loadMap()}

loadMap() {

 let location : LatLng = new LatLng(xxxxx,yyyyyy); 
 const markerOptions: MarkerOptions = {
   position: location, 
   title: 'Dubai'
 };





this.map = new GoogleMap('map', {
          'backgroundColor': 'white',
          'controls': {
            'compass': true,
            'myLocationButton': true,
            'indoorPicker': true,
            'zoom': true
          },
          'gestures': {
            'scroll': true,
            'tilt': true,
            'rotate': true,
            'zoom': true
          },
          'camera': {
            'latLng': location,
            'tilt': 30,
            'zoom': 15,
            'bearing': 50
                    },
        });
this.map.addMarker(markerOptions).then(data => {data.showInfoWindow();});
this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => console.log('Map is ready!'));

}
}

Answer №1

To view my solution, click on this link: https://github.com/driftyco/ionic-native/issues/1444

I implemented the native google maps feature using the documentation from https://ionicframework.com/docs/native/google-maps/

Below is the code snippet I utilized:

import { Component,  AfterViewInit } from '@angular/core';
import { NavController } from 'ionic-angular';

import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 LatLng,
 CameraPosition,
 MarkerOptions,
 Marker
} from '@ionic-native/google-maps';

import { GoogleMapsLatLng } from 'ionic-native';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements AfterViewInit  {

    map: GoogleMap;

    constructor(public navCtrl: NavController) 
    {

    }

    // Load map only after view is initialized
    ngAfterViewInit() {
        this.loadMap();
    }

    loadMap() 
    {
         // Ensure to create the below structure in your view.html file
         // and assign a height (e.g. 100%) to it; otherwise, the map may not display
         // <ion-content>
         //  <div #map id="map" style="height:100%;"></div>
         // </ion-content>
        let location = new GoogleMapsLatLng(-34.9290,138.6010);

        this.map = new GoogleMap('map', {
          'backgroundColor': 'white',
          'controls': {
            'compass': true,
            'myLocationButton': true,
            'indoorPicker': true,
            'zoom': false
          },
          'gestures': {
            'scroll': true,
            'tilt': true,
            'rotate': true,
            'zoom': true
          },
          'camera': {
            'latLng': location,
            'tilt': 0,
            'zoom': 15,
            'bearing': 50
          }
        });

        this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() =>
        {
            console.log('Map is ready!');
            this.map.addMarker({
                'position': location,
                'visible': true,
                'title': "nesto",
                'markerClick': function(marker) {
                    marker.showInfoWindow();
                }
            });

        });
     }

}

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

Angular 8 bug: Requiring 2-3 arguments, received only 1

Currently deepening my knowledge in Angular and I encountered a situation within one of my services agree(id: string) { const headers = new HttpHeaders('Content-Type: application/json'); return this.HttpClient.put(`${this.apiUrl}/agree/` ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

Why is my terminal showing certain output when I execute the command npm start?

I have a burning question. Upon running npm start in angular2, what exactly am I witnessing on my terminal screen? Where is this information originating from? I'm referring to: [1] No detection of a `bs-config.json` or `bs-config.js` override file. D ...

How to use CSS to add a pseudo element to a table and position it outside of the parent's boundaries on the left

I am currently utilizing the "ag-grid" data-table library (along with Angular 2, although the framework is not crucial) which highlights a selected row (using the default class .ag-row) by adding the class .ag-row-selected to it. Each row contains numerous ...

Disable button attribute in Angular unit testing when form is not valid

I have successfully implemented the functionality to disable a button when the form is invalid and enable it when the form is filled in properly. However, I am encountering difficulties with testing this feature: Here is the test that I wrote: it('s ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Is it possible to eliminate the table borders and incorporate different colors for every other row?

Eliminating the table borders and applying color to alternate rows. Check out my code snippet: https://stackblitz.com/angular/dnbermjydavk?file=app%2Ftable-overview-example.ts. ...

The design of Next.js takes the spotlight away from the actual content on the

Recently, I've been working on implementing the Bottom Navigation feature from material-ui into my Next.js application. Unfortunately, I encountered an issue where the navigation bar was overshadowing the content at the bottom of the page. Despite my ...

I am in search of a method to rephrase the content while minimizing redundancy

I am looking to improve the code for handling two different conditions in the UI. Can someone suggest a better way to rewrite it? <i *ngIf="measures.length > 0"> <ul *ngFor="let m of measures"> <io-data-selection-row [text] ...

Unable to utilize React Icons component as an object value in typescript

Currently, as I develop my personal website using typescript and react, I am faced with an issue in the footer section. I have an array of objects with url and icon properties that I map through to display different icons on each iteration. Initially, this ...

After the transition to Angular 8, the functionality of testing with Jest seems to have

After upgrading our Angular version from 7 to 8, we encountered some issues when using Jest as our test runner. Our main objective now is to ensure that our build pipeline runs smoothly with our JavaScript tests. One error message we're facing is: An ...

Angular 2 error: "unknown element" issue persists despite exhausting all attempted solutions

Here's a typical scenario where I attempt to incorporate a component from another module : External component : import { Component, ViewEncapsulation, ElementRef, ViewChild, Input, Output, EventEmitter } from '@angular/core'; declare ...

What is the best way to employ the *ngIf directive in order to alter an image?

I'm in the process of developing an application using the following technologies. How can I implement the use of *ngIf directive to switch between two images? Here's a more detailed explanation: I have two images, one representing the male symbol ...

The functionality of allowEmpty : true in gulp 4.0 does not seem to be effective when dealing with

gulp.task("f1", () => { gulp.src([], {"allowEmpty": true}) .pipe(gulp.dest(location)); }) An error message pops up saying "Invalid glob argument:" when the code above is used. gulp.task("f1", () => { gulp.sr ...

Describing a property of an interface as the determined form of a conditional type that is generic

I am currently working on defining an interface that includes a method with a conditional function definition. For example: interface Example<T> { func: T extends string ? () => string : () => number; } class ExampleClass<T extends str ...

Creating a TypeScript interface that has keys determined by the elements in an array

My goal is to create a function that returns a record with keys specified by a string array. For example: // return type -> { itemA:SomeType,itemB:SomeType } const res = doThing(['itemA', 'itemB']) Do you think this is achievable? ...

Angular input field with the ability to add and remove multiple options

Users can enter multiple emails to be added to a list, and they have the option to remove emails from the list. ...

Storing Json data in a variable within Angular 2: a step-by-step guide

https://i.sstatic.net/2QjkJ.png Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wron ...

Hold on for the next observable before moving forward

Whether or not I should include any code in this post is uncertain. However, I am willing to do so if necessary. I currently have an Angular2 directive called MyDirective and a service named MyService. The service performs an http call within its construc ...

How to create a collapse feature that allows only one item to be open at a time in Angular

I developed an angular app with a collapse feature, but I noticed that multiple collapses can be open at once. I am utilizing Ng-Bootstrap collapse for this functionality. Below is the code snippet from the TS file: public isCollapsed = true; And here is ...