官术网_书友最值得收藏!

Retrieving map data through geolocation coordinates

In this recipe, we will examine how to render a map on the screen and generate a marker based on latitude and longitude coordinates reported by the device geolocation sensors using the Google Maps API for JavaScript.

Getting ready

Before we can continue with coding the application in this recipe, we must first prepare the project and obtain access to the Google Maps services:

  1. First, sign up for a Google Maps API key. Visit https://code.google.com/apis/console/ and log in with your Google account.
    Getting ready
  2. Select APIs & auth followed by APIs from the left-hand side menu and activate the Google Maps JavaScript API v3 service.
  3. Once the service has been activated, you must create a new credential. Go to APIs & auth | Credentials, and under Public API access select Create new Key. Select Server key and hit Create. A new key will be created for any IPS.
    Getting ready

We can now proceed with the recipe.

How to do it…

We'll use the device's GPS ability to obtain the geolocation coordinates, build and initialize the map canvas, and display the marker for our current position as follows:

  1. First, create a new PhoneGap project named maps by running the following command:
    phonegap create maps com.myapp.maps maps
    
  2. Add the device platform. You can choose to use Android, iOS, or both:
    cordova platform add ios
    cordova platform add android
    
  3. Add the geolocation plugin by running the following command:
    phonegap plugin add org.apache.cordova.geolocation
    
  4. Open www/index.html and clean up unnecessary elements; so you have the following:
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <meta name="format-detection" content="telephone=no" />
            <meta name="msapplication-tap-highlight" content="no" />
            <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height,
            target-densitydpi=device-dpi" />
            <title>You are here</title>
        </head>
        <body>
    
            <script type="text/javascript" src="cordova.js"></script>
            <script type="text/javascript">
                // Custom code goes here
            </script>
        </body>
    </html>
  5. Include the required JavaScript for the Google Maps API under the Cordova reference. Append your API key to the query string in the script src attribute:
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=your_api_key&sensor=true">
    </script>

    Note

    When we included the Google Maps API JavaScript into our document, we set the sensor query parameter to true. If we were only allowing the user to manually input coordinates without automatic detection, this could have been set to false. However, we are using the data obtained from the device's sensor to automatically retrieve our location.

  6. Start creating the custom code within the JavaScript tag block. First, create the event listener to ensure the device is ready and also create the onDeviceReady method, which will run using the listener:
    // Set the event listener to run when the device is ready
    document.addEventListener(
    "deviceready", onDeviceReady, false);
    
    // The device is ready, so let's
    // obtain the current geolocation data
    function onDeviceReady() {
        navigator.geolocation.getCurrentPosition(
            onSuccess,
            onError
        );
    }
  7. Next, write the onSuccess method, which will give you access to the returned location data via the position object.
  8. Take the latitude and longitude information obtained from the device geolocation sensor response and create a latLng object to be sent into the Map when the component is initialized.
  9. Then set the options for the Map, setting its center to the coordinates set into the latLng variable. Not all of the Google Maps controls translate well to the small screen, especially in terms of usability. You can define which controls you would like to use. In this case, accept zoomControl but not panControl.
  10. To define the Map itself, reference a div element and pass it through the mapOptions previously declared.
  11. To close this method, create a Marker to display at the exact location as set in the latLng variable:
    // Run after successful transaction
    // Let's display the position data
    function onSuccess(position) {
    
        var latLng  =
                new google.maps.LatLng(
                        position.coords.latitude,
                        position.coords.longitude);
    
        var mapOptions = {
                    center: latLng,
                    panControl: false,
                    zoomControl: true,
                    zoom: 16,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
    
        var map = new google.maps.Map(
                    document.getElementById('map_holder'),
                                mapOptions
                            );
                        
        var marker = new google.maps.Marker({
                    position: latLng,
                    map: map
                });
    
    }
  12. To ensure that you correctly handle any errors that may occur, include the onError function, which will display the specific string message according to the error within a div element:
    // Run if we face an error
    // obtaining the position data
    function onError(error) {
    
        var errString   =   '';
    
        // Check to see if we have received an error code
        if(error.code) {
            // If we have, handle it by case
            switch(error.code)
            {
                case 1: // PERMISSION_DENIED
                    errString   =
                        'Unable to obtain the location information ' +
                        'because the device does not have permission '+
                        'to the use that service.';
                break;
                case 2: // POSITION_UNAVAILABLE
                    errString   =
                        'Unable to obtain the location information ' +
                        'because the device location could not be ' +
                        'determined.';
                break;
                case 3: // TIMEOUT
                    errString   =
                        'Unable to obtain the location within the ' +
                        'specified time allocation.';
                break;
                default: // UNKOWN_ERROR
                    errString   =
                        'Unable to obtain the location of the ' +
                        'device due to an unknown error.';
                break;
            }
    
        }
    
        // Handle any errors we may face
        var element = document.getElementById('map_holder');
        element.innerHTML = errString;
    }
  13. With the body tag, include the div element into which the map will be displayed:
    <body>
        <div id="map_holder"></div>
    </body>
  14. Finally, add a style block within the head tag to supply some essential formatting to the page and the map element:
    <style type="text/css">
        html { height: 100% }
        body { height: 100%; margin: 0; padding: 0 }
        #map_holder { height: 100%; width: 100%; }
    </style>
  15. Upon running the application on the device, you will see a result similar to the following:
    How to do it…

How it works...

Thanks to the use of exposed mapping services such as Google Maps, we are able to perform geolocation updates from the device and use the obtained data to create rich, interactive visual mapping applications.

In this example, we centered the Map using the device coordinates and also created a Marker overlay to place upon the mark for easy visual reference.

The available APIs for mapping services such as this are incredibly detailed and contain many functions and methods to assist you in creating your location-based tools and applications. Some services also set limits on the number of requests made to the API, so make sure you are aware of any restrictions in place.

Static maps

In this recipe, we used the dynamic Google Maps API. We did this so that we could use the zoom controls and provide our user with a certain level of interaction by being able to drag the map. As an alternative, you could use the Google Static Maps service, which simplifies the code needed to generate a map and will return a static image showing the location.

You can choose to use an API key with this service, but it is not required. You will still have to enable the API in the same way the API access was enabled at the start of this recipe.

Consider the following code. It is an amendment to the onSuccess method, which runs after the geolocation data has been obtained:

// Run after successful transaction
// Let's display the position data
function onSuccess(position) {
    var mapOutput = '<img src="http://maps.googleapis.com/maps/api/staticmap?center='+position.coords.latitude+','+position.coords.longitude+'&zoom=12&size=300x300&scale=2&sensor=true">';
    var element = document.getElementById('map_holder');
    element.innerHTML = mapOutput;
}

Here, instead of creating the coordinates, the map, and the markers as in the earlier code listing, we simply request an image source using the Static Maps API, and send in the coordinates, image size, and other data as parameters.

By using the Static Maps API, you lose the interactivity offered through the dynamic map, but you gain an incredibly simple, easy-to-use service that requires very little code to achieve results.

There's more…

We used the Google Maps API for JavaScript in this recipe. There are variations in the API level offered by Google, and other mapping systems are also available through other providers, such as MapQuest, MultiMap, and Yahoo! Maps. Explore the alternatives and experiment to see if a particular solution suits your application better than others.

See also

主站蜘蛛池模板: 富平县| 浦东新区| 广平县| 大港区| 芜湖市| 疏勒县| 长春市| 永登县| 陆丰市| 双柏县| 隆德县| 聊城市| 玉环县| 上虞市| 古蔺县| 循化| 岳西县| 昌邑市| 罗田县| 高青县| 镇安县| 马山县| 美姑县| 昭苏县| 麻城市| 河西区| 乌兰察布市| 夏津县| 通辽市| 马鞍山市| 息烽县| 牙克石市| 安国市| 尖扎县| 绿春县| 昌宁县| 平塘县| 云浮市| 通州市| 祁连县| 襄樊市|