Ionic 3: Incorporating Baidu map functionality exclusively for web browsers

My current project with Ionic 3 involves incorporating the npm package angular2-baidu-map to display maps of China mainland.

I have successfully obtained an API key for Baidu Maps (for the JS API), and the map functions perfectly in a browser (via ionic serve -l), but once the app is compiled and installed on a physical device, the map fails to appear.

Upon further investigation, it seems that the API is sending requests to file://api.map.baidu.com regardless of the settings in the protocol map initialization option.

For example, the Safari developer tools' console displays numerous messages like:

The requested URL was not found on this server. file://api.map.baidu.com/api?v=2.0&ak=...&callback=baidumapinit&s=0 Failed to load resource: The requested URL was not found on this server.

Edit: included code snippets

Although I initially tested the plugin with the demo code, for completeness, I've provided it here as well.

HTML code

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Baidu map</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<baidu-map ak="{{ak}}"
     [options]="opts" [offline]="offlineOpts" 
     (onMapLoaded)="loadMap($event)" 
     (onMarkerClicked)="clickMarker($event)" 
     (onClicked)="clickMap($event)"></baidu-map>
</ion-content>

Typescript

map-baidu.module.ts

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { MapBaiduPage } from './map-baidu';
import { TranslateModule } from '@ngx-translate/core';
import { BaiduMapModule } from 'angular2-baidu-map';

@NgModule({
  declarations: [
    MapBaiduPage,
  ],
  imports: [
    IonicPageModule.forChild(MapBaiduPage),
    TranslateModule.forChild(),
    BaiduMapModule
  ],
})
export class MapBaiduPageModule {}

map-baidu.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { OfflineOptions, ControlAnchor, NavigationControlType } from 'angular2-baidu-map';

@IonicPage()
@Component({
  selector: 'page-map-baidu',
  templateUrl: 'map-baidu.html',
})
export class MapBaiduPage {

  public ak:string = '<your Baidu JS API key here>';
  opts: any;
  offlineOpts: OfflineOptions;

  constructor(public navCtrl: NavController, public navParams: NavParams) { }

  ionViewDidLoad() {
    console.log('ionViewDidLoad MapBaiduPage');
  }

  loadMap(map:any){
    console.log('> loadMap:', map);
  }
  clickMap(e:any){
    console.log('> clickMap:', e.point.lat, e.point.lng);
  }

  clickMarker(marker:any){
    console.log('> clickMarker:', marker);
  }

  ngOnInit() {
    this.opts = {
      // protocol:'https:', // changes nothing
      center: {
        longitude: 121.506191,
        latitude: 31.245554
      },
      zoom: 12,
      markers: [{
        longitude: 121.506191,
        latitude: 31.245554,
        title: 'Where',
        content: 'Put description here',
        enableDragging: true
      }],
      geolocationCtrl: {
        anchor: ControlAnchor.BMAP_ANCHOR_BOTTOM_RIGHT
      },
      scaleCtrl: {
        anchor: ControlAnchor.BMAP_ANCHOR_BOTTOM_LEFT
      },
      overviewCtrl: {
        isOpen: true
      },
      navCtrl: {
        type: NavigationControlType.BMAP_NAVIGATION_CONTROL_LARGE
      }
    };

    this.offlineOpts = {
      retryInterval: 5000,
      txt: "Network unavailable"
    };
  }
}

Any suggestions?

Answer №1

After reviewing the sourcecode, it appears that the component determines the protocol to use in the following way:

export var loader = function (ak, offlineOpts, callback, protocol) {
  var realProtocol = protocol || location.protocol;

If no protocol is provided, it defaults to the protocol of the page (such as file:// for Ionic or localhost:// for WKWebview).

In your question, you mentioned attempting to pass a different protocol by including it in the opts object. However, the BaiduMap Component expects the protocol to be a separate @Input:

export class BaiduMap implements OnInit, OnChanges {
  @Input() ak: string;
  @Input() protocol: string;
  @Input() options: MapOptions;

To make the necessary change, update your component template as follows:

<baidu-map ak="{{ak}}"
  [options]="opts" 
  [offline]="offlineOpts" 
  [protocol]="'https'" // the extra quotation marks are needed 
  (onMapLoaded)="loadMap($event)" 
  (onMarkerClicked)="clickMarker($event)" 
  (onClicked)="clickMap($event)">
</baidu-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

Retrieving the innerHTML or innerText of a structural DOM element generated by *ngFor in Selenium

Having trouble accessing the innerHTML/innerText of a structural DOM element, only getting a commented element instead of the child elements. <div class="snap-box"> <label class="snap-heading">Recommendations</label> <div class="r ...

Retrieve user details from a NextJS application following a successful Keycloak authentication on a Kubernetes cluster

I've been attempting to retrieve the authenticated user information in my NextJS app after being redirected to it following a successful Keycloak login on a different tab located at localhost:8080/auth. The ingress (entry point) is responsible for ch ...

Utilizing models to establish the data type of an Observable within Angular

I have a simple query regarding a service. I have a method called getAllArticlesFromDb in my service that retrieves data from an API using an HTTP GET call. Here is the code for the method: article.service.ts getAllArticlesFromDb() : Observable<any> ...

A declaration file in Typescript does not act as a module

Attempting to create a TypeScript declaration file for a given JavaScript library my_lib.js : function sum(a, b) { return a + b; } function difference(a, b) { return a - b; } module.exports = { sum: sum, difference: difference } my_lib.d.ts ...

Utilize Hostbinding in Angular to Inject Style Declarations

Is there a way to efficiently inject multiple style declarations into a component using the @HostBinding decorator? I've been attempting the following: @HostBinding('style') get style(): CSSStyleDeclaration { return { background: &apo ...

Type 'Partial' cannot be assigned a value when combining interfaces with generic types

Consider the following scenario: class Table<ValuesType extends DefaultTableValues = DefaultTableValues>{ public values: ValuesType; constructor(initialValues:ValuesType) { this.values=initialValues; } public set(newValues:Pa ...

It takes two clicks for the text to change on the button in Angular

As a newcomer to angular, I am working on a quiz application where I've encountered an issue. When I click a button, it requires two clicks to function properly. The first click works fine, but subsequent clicks on the next and back buttons need to be ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

Encountered an issue while loading the discovery document for the integration of AD FS using angular-oauth2-oid

I'm currently developing an angular SPA that requires authentication using AD FS, with Spring Boot as the backend. this.oauthService.configure({ redirectUri: window.location.origin + '/app/search', requireHttps: true, scope ...

In TypeScript, both 'module' and 'define' are nowhere to be found

When I transpile my TypeScript using "-m umd" for a project that includes server, client, and shared code, I encounter an issue where the client-side code does not work in the browser. Strangely, no errors are displayed in the browser console, and breakpoi ...

Customizing MUI V5 Variants

I'm having trouble customizing the variant options in MUIPaper, and I can't figure out what mistake I'm making. The available types for the component are: variant?: OverridableStringUnion<'elevation' | 'outlined', Pape ...

Verify the functionality of a specific method invoked within another method through unit testing

I currently have a method in my Angular application that is triggered upon clicking. Inside this method, I pass a value to another private method. .ts file public onViewItem(item: Results): void { const ids = [item.data['id']]; this.anot ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

Deriving types from object combinations

Can the Foo type be 'flattened' to return { A?: string; B? number } in the code snippet below? type Foo = { A: string } | { B: number } type Flatten< T, Keys extends keyof T = T extends any ? keyof T : never, > = { [K in Keys]?: T[K] } ...

Angular 2 GET request returns a 404 error

I have been attempting to reproduce the ngPrime datatable demo from this Github repository. Currently, I am working with the most recent version of Angular (4) and using angular-cli in development mode. Placing a JSON file into my app folder where the serv ...

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

Establishing foreignObject coordinates in Angular

Struggling with setting the position (x, y) for foreignObject in Angular. I have attempted the following: <foreignObject width="65" height="50" x="{{position?.x}}" y="{{position?.y}}"> <div class="c ...

When a shared service is used for parent component binding with *ngIf, the update is not reflected when triggered from the child component

I have two components, a main parent component and a child component. The parent component contains a menu. Even when the child component says this.service.isMenuVisible(false), the menu remains visible in the parent component without any errors being thro ...

Utilizing Arrays in Typescript within the Angular Framework

I have developed a Rest API that provides data to populate two drop-down lists in a form. The information retrieved from the API is grabbed by the Angular backend and assigned to the respective drop-downs. Rather than making separate Get requests for each ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...