Tencent Location service provides leading LBS services and solutions for all kinds of application manufacturers and developers. There are JavaScript apis for Web applications, various SDKS suitable for mobile Native apps, WebService interfaces, plug-ins suitable for small programs and various map apis.

directory

Access to the guide

Map Component (H5)

Map javaScript API

Location of the SDK (Android SDK | IOS SDK) positioning

Map the SDK (map of Android SDK | map of IOS SDK)

WebService API: Reference documentation

Landlord authentication channel:

Q&A

Tencent Location service console

Industry Solutions

Tencent Location service technology tutorial

Tencent location feature product examples


 

Access to the guide

Access steps: (Fast channel: Tencent location official website)

How do you choose the API as a developer?

Map Component (H5)

Mobile component H5, complete application, do not need developers to develop, — “reference documentation

Location display component that displays one or more location points on a map. Data sources are supported in three ways: passing data through urls, map retrieval data, and custom data. You can display details such as the name and address of each location point, view street view information of the location point or initiate route planning to the location.

Such as:

Call address:

https://apis.map.qq.com/tools/poimarker?type=0&marker=coord:39.96554, 116.26719; Title: chengdu; Addr: 32, haidian district of Beijing changfu promotes hospital | coord: 39.87803, 116.19025; Chengdu Park; Addr: 15 shooting range road, fengtai district, Beijing China Beijing park expo garden | coord: 39.88129, 116.27062; Title: Old Chengdu; Addr: Beijing fengtai yue area sit top of mei road garden on the 6th floor base business | coord: 39.9982, 116.19015; Title: Beijing Garden Expo Park Chengdu Park; Addr: Beijing Fengtai District Garden Expo garden &key=yourkey&referer=myappCopy the code

Map javaScript API

For browser side map display and application, compatible with mobile phone and PC side — “reference documentation

JavaScript API V2 can be used to add the web interactive street, maps, can well support PC and mobile devices, small stature, animation smooth smooth, dynamic, provide map operations, mark, site search, travel planning, address resolution, street interface, such as a feature-rich, free of charge and additional tools. JavaScript API V2 is a free service and can be called by any website that provides free access.

The visual component is an additional library of the JSAPI that is specified in the libraries parameter in the load JavaScript API service request

< script charset = "utf-88"SRC =" HTTPS:/ / map.qq.com/api/js?v=2.exp&key=YOUR_KEY&libraries=visualization ">
Copy the code

The interfaces are defined in q.maps.visualization global variables and need to be used after map initialization

var map = new qq.maps.Map(container, mapOpts);
var dots = new qq.maps.visualization.Dots({
    map: map
});
dots.setData(data);
Copy the code

For example: we want to display a 603×300 map centered on Tiananmen Square in Beijing:

<! DOCTYPEhtml>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sun Jiaotou tests a map of Tian 'anmen</title>
<meta name="viewport" content="Width =device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<style type="text/css">
html.body{
    width:100%;
    height:100%; {} *margin:0px;
    padding:0px;
}
body.button.input, select, textarea {
    font: 12px/16px Verdana, Helvetica, Arial, sans-serif;
}
p{
    width:603px;
    padding-top:3px;
    overflow:hidden;
}
.btn{
    width:142px;
}
#container{
    width:100%;
    height:100%;
}
</style>
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<script>

window.onload = function(){

// Load the map directly


    // Initialize map function custom function name init
    function init() {
        Call the q.maps.map () constructor to get the map display container
         var map = new qq.maps.Map(document.getElementById("container"), {
            center: new qq.maps.LatLng(39.916527.116.397128),      // The central geographic coordinates of the map.
            zoom:8                                                 // The central geographic coordinates of the map.
        });
    }

    // call the initialization function map
    init();


}
</script>
</head>
<body>
<! Define map display container -->
<div id="container"></div>
</body>
</html>
Copy the code

Effect:

Loading the map API:

Method 1: Page import directly.

<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
Copy the code

Method 2: Load the JavaScript API asynchronously

<! DOCTYPEhtml>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Asynchronously loading maps</title>
<meta name="viewport" content="Width =device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<style type="text/css">
html.body{
    width:100%;
    height:100%; {} *margin:0px;
    padding:0px;
}
body.button.input, select, textarea {
    font: 12px/16px Verdana, Helvetica, Arial, sans-serif;
}
p{
    width:603px;
    padding-top:3px;
    overflow:hidden;
}
#container{
    width:100%;
    height:100%;
}
.btn{
    width:142px;
}
</style>
<script>


function init() {
  // Set the map center point
  var myLatlng = new qq.maps.LatLng(39.916527.116.397128);
  // Define factory mode functions
  var myOptions = {
    zoom: 8.// Set the map zoom level
    center: myLatlng,      // Set the center point style
    mapTypeId: qq.maps.MapTypeId.ROADMAP  For details about setting the map style, see MapType
  }
  // Get the DOM element to add map information
  var map = new qq.maps.Map(document.getElementById("container"), myOptions);
}
  // Asynchronously load map library function files
function loadScript() {
  // Create the script tag
  var script = document.createElement("script");
  // Set the type attribute for the tag
  script.type = "text/javascript";
  // Set the link address of the label
  script.src = "https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&callback=init";
  // Add tags to dom
  document.body.appendChild(script);
}
  
window.onload = loadScript;    // dom document loading ends
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Copy the code

Effect:

It has the following functions:

Overlay Powerful additional libraries Define your own map
Provide point annotation, polyline, circle, polygon, information window and other coverings, users can define personalized map. Provides mouse drawing toolbox, geometric operations, coordinate conversion, text input hints and other additional libraries. Users can customize map types, use their own data or pictures, and customize rules for cutting maps and taking maps.

 

Positioning the SDK (Android positioning the SDK |   IOS positioning the SDK)

Tencent Map location SDK is a set of application programming interface based on Android 4.1 and above. Through this interface, you can easily use Tencent map location service to build LBS applications.

The positioning SDK includes GPS positioning and network positioning, realizing the query of longitude and latitude coordinate deflection and POI name, address or administrative division of the current location. Mobile cache strategy is adopted to save traffic and power.

The Positioning SDK is intended for developers with some Android programming experience and an understanding of object-oriented concepts.

This Android example uses the background location mode:

When a user process is in the background, it sometimes needs to use location services, but the Android system has many restrictions on location when the application is in the background. Therefore, we raise the process level by setting the foreground Service, so that the location Service is transferred from the background to the foreground.

1. Add the Service declaration to the manifest

<service android:name="com.tencent.map.geolocation.s" />
Copy the code

 

2. Before starting the location, invoke enableForegroundLocation

mLocationManager.enableForegroundLocation(LOC_NOTIFICATIONID, buildNotification());
mLocationManager.requestLocationUpdates(request, this, getMainLooper());
Copy the code

Build Notification (where the parameters to enableForegroundLocation are an integer NotificationID and one is an instance of Notification).

private Notification buildNotification(a) {
    Notification.Builder builder = null;
    Notification notification = null;
    if (android.os.Build.VERSION.SDK_INT >= 26) {
        // Notification is modified on Android O. If targetSDKVersion>=26 is set, you are advised to use this method to create Notification bars
        if (notificationManager == null) {
            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        String channelId = getPackageName();
        if(! isCreateChannel) {NotificationChannel notificationChannel =new NotificationChannel(channelId,
                    NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            notificationChannel.enableLights(true);// Whether to display small dots in the upper right corner of desktop icon
            notificationChannel.setLightColor(Color.BLUE); // Dot color
            notificationChannel.setShowBadge(true); // Whether to display notifications for this channel when pressing the desktop icon for a long time
            notificationManager.createNotificationChannel(notificationChannel);
            isCreateChannel = true;
        }
        builder = new Notification.Builder(getApplicationContext(), channelId);
    } else {
        builder = new Notification.Builder(getApplicationContext());
    }
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("LocationDemo")
            .setContentText("Running in background")
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setWhen(System.currentTimeMillis());

    if (android.os.Build.VERSION.SDK_INT >= 16) {
        notification = builder.build();
    } else {
        notification = builder.getNotification();
    }
    return notification;
}
Copy the code

3. After the stop position, call disableForegroundLocation stopped at the front desk service

LocationManager.removeUpdates(this);
mLocationManager.disableForegroundLocation(true);
Copy the code

Permission configuration (configure the following permissions in the manifest file 🙂

<! -- Get accurate position by GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<! -- Get rough location through network -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<! -- Access the network. Some location information needs to be retrieved from the web server -->
<uses-permission android:name="android.permission.INTERNET" />
<! -- Access WiFi status. Need WiFi information for network location -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<! -- Change the WiFi status. To initiate WiFi scan, WiFi information is required for network location -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<! Access network status and check network availability. Network operator information is required for network location -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<! Network access changes, need some information for network location -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<! Device ID is required for network location -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<! -- Support A-GPS assisted positioning -->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<! -- Log -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Copy the code

Note: As the Android version is upgraded, the use of permissions also changes. For details, please refer to the adaptation documents for each Version of Android in the practical documentation.

Location service is a function heavily dependent on user authorization, so the way of obtaining user permissions must be fully considered in App design and users should be reasonably guided to grant permissions.

 

Tencent iOS location SDK provides location functions that do not rely on map location. Developers can easily add location functions to applications in scenarios without map display. IOS location SDK provides single location, continuous location, inverse geographic information and other functions. Compatible with iOS7.0 or later.

Locating Permission Application

(1) need to apply for an apiKey in https://lbs.qq.com/dev/console/key/add, corresponding on the TencentLBSLocationManager apiKey attribute set can be used.

(2) need to be in the info. Append NSLocationWhenInUseUsageDescription plist or NSLocationAlwaysUsageDescription field, to apply for the position.

(3) positioning allowsBackgroundLocationUpdates said whether to allow the background. The default value is NO. Only works on iOS 9.0 and later. When set to YES, ensure that Location updates in Background Modes are selected, otherwise an exception will be thrown. Note, if you do not set to YES, you do not need to apply for this permission, otherwise the audit will not pass!

Importing location packages: Copy the tencentlbs. framework file to the project directory of your APP and select Build Phases -> Link Binary With Libraries -> Add -> Add from the Xcode Target Other…” -> Select the tencentlbs. framework directory and add.

Import system library files: TBD Add -lstdc++.6.0.9 to Build setting-linking – Other Linker Flags. -lsqlite3(note: above Xcode9, these two libraries are no longer needed).

- (void)configLocationManager
{
    self.locationManager = [[TencentLBSLocationManager alloc] init];
 
    [self.locationManager setDelegate:self];
 
    [self.locationManager setApiKey:@" apiKey corresponding to application"];
 
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
 
    // This property can be set to YES if background positioning is required.
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
 
    // If the POI information is required, set it according to the required level. The location result will be returned according to the set POI level, for example:
    [self.locationManager setRequestLevel:TencentLBSRequestLevelName];
 
    // The requested location permission is valid only if it corresponds to the requested location permission in info.list
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if (authorizationStatus == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization]; }}// Single location
- (void)startSingleLocation {
    [self.locationManager requestLocationWithCompletionBlock:
        ^(TencentLBSLocation *location, NSError *error) {
            NSLog(@ "% @, % @, % @", location.location, location.name, location.address);
        }];
}
 
// continuous positioning
- (void)startSerialLocation {
    // Start positioning
    [self.locationManager startUpdatingLocation];
}
 
- (void)stopSerialLocation {
    // Stop positioning
    [self.locationManager stopUpdatingLocation];
}
 
- (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager
                 didFailWithError:(NSError *)error {
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if (authorizationStatus == kCLAuthorizationStatusDenied ||
        authorizationStatus == kCLAuthorizationStatusRestricted) {
        [self.displayLabel setText:"Location permission not enabled!"];
 
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@ "tip"
                                                                       message:@" Location permission is not enabled, yes or no?"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@ "is"
                                                  style:UIAlertActionStyleDefault
                                                handler:^(UIAlertAction * _Nonnull action) {
            if([[UIApplication sharedApplication]canOpenURL:
                [NSURL URLWithString:UIApplicationOpenSettingsURLString[[]]) {UIApplication sharedApplication] openURL:
                    [NSURL URLWithString:UIApplicationOpenSettingsURLString]]. }}]]; [alert addAction:[UIAlertAction actionWithTitle:@ "no"
                                                  style:UIAlertActionStyleDefault
                                                handler:^(UIAlertAction * _Nonnull action) {
        }]];
 
        [self presentViewController:alert animated:true completion:nil];
 
    } else{[self.displayLabel setText:[NSString stringWithFormat:@ "% @", error]]; }} - (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager
                didUpdateLocation:(TencentLBSLocation *)location {
    // Location result
    NSLog(@"location:%@", location.location);
}
Copy the code

Error status prompt:

typedef NS_ENUM(NSUInteger, TencentLBSLocationError) {
    TencentLBSLocationErrorUnknown = 0./ /! < error code, indicating that the current location is unknown, but will always try to obtain
    TencentLBSLocationErrorDenied = 1./ /! < Error code: indicates that the locating permission is forbidden
    TencentLBSLocationErrorNetwork = 2./ /! < Error code: indicates a network error
    TencentLBSLocationErrorHeadingFailure = 3./ /! < error code, indicating orientation cannot be confirmed
    TencentLBSLocationErrorOther = 4./ /! < Error code, unknown error
};
Copy the code

Map the SDK(Map of the Android SDK |  The IOS SDK map)

It is used to embed maps and applications in mobile apps.

Android 3D is suitable for scenarios that rely heavily on maps, such as navigation, taxi-hailing and chauffeuring. It can also be used in wearable devices. 2D is suitable for auxiliary location display scenarios, such as sending location, address display, and track display. Developers who are sensitive to package size are recommended to use 2D.

AndroidStudio configuration

Step 1: get the Key points I get Key > >] (/ mobile/androidMapSDK/developerGuide/getKey)

Step 2: Create an AndroidStudio project Create an empty Android project in AndroidStudio.

There are two main ways to integrate Tencent map SDK in AndroidStudio project: 1. Manually import the JAR package and so library of Tencent Map SDK into project 2. Configure Maven or jCenter repository to integrate the SDK through Gradle

We recommend users to use the second method, that is, import Tencent map SDK through Maven. We will introduce the following two methods in detail.

Add the SDK by copying the JAR package and so library

  1. First of all, please get Tencent Map SDK for Andorid and its demo here.
  2. Decompress the downloaded zip package and copy the file. Take the map function of version 4.3.4 as an example. After decompressing, a liBS folder is obtained. This folder contains the 0700-mapsdK-release4.3.4.b8edc92f.jar file and a jniLibs folder (the file contains all so library files)
  3. Copy the “*.jar” file from the libs directory to the corresponding app/libs/ folder of the AndroidStudio project.


Right-click the jar package and select Add As Library to pop up the following window:

 

Click OK and the following image will show the successful import:

 

  1. Copy all files in the jniLibs directory to the app/ SRC /main/jniLibs/ directory corresponding to the AndroidStudio project in the original format.



TencentMap Android SDK also provides a map component library TencentMapUtils, currently the map component contains point aggregation component, car smooth moving component. component

IOS automatic deployment is as follows:

When users use Tencent Map iOS SDK to support project development, they can add the SDK to the project through Cocoapods automatic deployment. Currently, only Tencent Map iOS SDK 4.2.6.2 or later is supported for automatic deployment.

Get CocoaPods

CocoaPods is a third-party library resource manager that supports Swift and Objective-C projects. Users can access Tencent Map iOS SDK through CocoaPods.

If you already have CocoaPods installed, skip to step 2: Install the SDK through CocoaPods.

1. Configure the Ruby software source

You are advised to install CocoaPods through Ruby. As a result of the default ruby source software “mirrors.tencent.com/rubygems/” by wall cause CocoaPods installation failure, so you need to update the ruby source. Run the following commands in sequence:

# add TUNA source and remove the default source gem sources - add http://mirrors.tencent.com/rubygems/ - remove https://rubygems.org/ Gem sources-l gem sources-lCopy the code

After the preceding command is executed, the update succeeds if the following information is displayed

*** CURRENT SOURCES *** 
http://mirrors.tencent.com/rubygems/
Copy the code

 

2. To upgrade the gem

Update the gem version to the latest to ensure that Cocoapods is installed successfully

sudo gem update --system
Copy the code

 

3. Install Cocoapods

Install Cocoapods using the following command:

sudo gem install -n /usr/local/bin cocoapods pod setup
Copy the code

Note: The Cocoapods installation process may take a long time and may fail due to network conditions. If the installation fails, try again

Install the SDK through CocoaPods

1. Create Podfile

Create a file named Podfile in the folder of the current project file (.xcodeProj). The Podfile reads as follows:

Platform :ios, "8.0" # target "QMapKitDemo" do # project name pod 'Tencent-MapSDK' # MapSDK end #end #target "QMapKitDemo2" do #target "QMapKitDemo2" do #target "QMapKitDemo2" do # # pod 'Tencent-MapSDK' # MapSDK #endCopy the code

 

2. Install the SDK

Install the SDK pod install to ensure that the local map SDK is the latest pod repo updateCopy the code

After the command is successfully executed, the.xcworkspace file is generated and opened to start the project (note that the.xcodeproj file cannot be opened at the same time, for example:

 

3. Upgrade the SDK

If you have installed the Tencent Maps iOS SDK through automatic deployment and want to update to the latest version, you can run the following command in the Podfile directory:

Pod Repo update # is used to ensure that the local map SDK is the latest POD UpdateCopy the code

 

4. Install the SDK of the specified version

Automatic deployment currently only supports maps iOS SDK 4.2.6.2 and later. If you want to use the specified SDK, you need to modify the Podfile.

Platform :ios, "8.0" # target "QMapKitDemo" do # '~> 4.2.6.2' # Change or add 3D SDK version number here endCopy the code

Then execute the command:

Install the SDK pod install to ensure that the local map SDK is the latest pod repo updateCopy the code

WebService API: Reference documentation

Tencent Map WebService API is based on HTTPS/HTTP protocol data interface, developers can use any client, server and development language, according to Tencent Map WebService API specifications, on-demand construction of HTTPS requests, And obtain the result data (currently support JSON/JSONP return).

Note: this has call quota restrictions (other products have no call restrictions) : lbs.qq.com/service/web…

Tencent location service API Key is used to uniquely identify the developer’s identity when invoked. API Key is common to all products, that is to say, the same Key can be used in map SDK, JavascriptAPI, WebServiceAPI and other products. It can be independently enabled for different products. Assuming that one of your keys only calls the map SDK, you can turn off other products in the Key configuration interface to reduce security risks.

 

In the Key setting, check the WebService check box to enable the product. This Key can call the WebServiceAPI service only when the service is not enabled.

{ "status": 199."message": "Webservice is not enabled for this key" }
Copy the code

To apply for the key

Example:

https:/ / apis.map.qq.com/ws/place/v1/search?keyword= hotel & boundary = basis (39.908491, 116.374328, 1000) & key = OB4BZ - D4W3U PJWW B7VVO - 4-6 TKDJ-WPB77
Copy the code

For details about how to configure multiple security policies, see Security Policy Description

Landlord authentication channel:

If you are the operator, owner, etc. of a site, you can apply for certification by yourself. If you pass the examination, you can show the application site and entrance on the map

All kinds of enterprises and institutions, individual industrial and commercial businesses, to their business places, entity stores hope to be included in Tencent map, can apply for merchant annotation. After submitting merchant labeling, the information you fill in will be seen by all users, so please confirm that the location information you submit complies with relevant national laws (such as military facilities, confidential locations and other information cannot be submitted according to relevant national laws). If there is any mistake in the labeling of an existing merchant, the merchant may submit the location for correction and modification.

Q&A

Frequently asked Questions about landlord certification

Faqs about access authentication

Tencent Location service console

This article takes you to understand the development and access of Tencent location service

Industry Solutions

Reference documentation

Tencent Location service technology tutorial

Reference documentation

Tencent location feature product examples

Reference documentation

 

Well, this period of Tencent location service content to share here, we will see you next time!

Tencent location services can be quickly entered from the channel below, fill in the invitation code for more technical support!

Tencent location service registration address: lbs.qq.com? Lbs_invite =3Z2RFL3

Invitation code: 3Z2RFL3