In the Ionic program, if you need to locate the city where the user is located, you can use the following method.
In the Ionic program, the introduction of Baidu Map API. Open file: \src\index.html. In head tag, add the following code, and note replace "your key" with the key you requested.
<script type= "Text/javascript" src= "http://api.map.baidu.com/api?v=2.0&ak= Your Keys" ></script>
My side assumes that you have created a map page and loaded the map module into the app module. (as is not understood here, refer to this article Https://www.jianshu.com/p/a7b4bcb5bd66) front-end display. Here I put the city name on the header of the page.
< ion-header > < ion-navbar color = "PRIMARY" > < ion-title class = "Rightfloat" > your city: {{localcityname}}</ ion-title > </ ion-navbar > </ ion-header >
In the Ionic program, open the file \src\pages\map\map.ts, the following code implements the load city name.
DeclarevarBmap;declarevarbmaplib; @IonicPage () @Component ({selector:' Page-map ', Templateurl:' Map.html ',}) Export class Mappage {localcityname:string; Constructor (public navctrl:navcontroller) {} ionviewdidload () {varMycity =Newbmap.localcity (); Mycity.get (function(Result) {varCityName =Result.name; //use Localstoage to store cityname. This.localcityname = CityName is not allowed here, because this refers to the current class, that is, function (result).Localstorage.setitem (' currentcity ', CityName); returnCityName;}); //delay of 500 milliseconds to fetch cityname stored in LocalstorageSetTimeout (() = { This. Localcityname = Localstorage.getitem (' currentcity '); }, 500); }
By delaying the function, this ensures that the localcityname is valued when the map page loads for the first time. The current city can be displayed instead of being displayed empty.
The settimeout delay function is used to solve the problem of NULL localcityname the first time the page is loaded. How you have a better approach, welcome message discussion.
Ionic uses the Baidu Map API to locate the city example where the user is currently located