Home » Sencha Touch » Sencha touch Maps

Sencha touch Maps

Welcome to the sixth module of this series. In this module we will learn about Sencha touch maps, how can we add map to our application, how can we display the marker on map. We will also learn about how to use geocoding to get the address value, how to get current location. Moving forward we will learn about how to add different layers in map and at last we will learn how to add marker click event.

Sencha touch has an ability to display maps. Internally sencha touch uses Google maps API which allows developers to include any type of map in their application.

Below snippet will add Google map in your application.

Ext.Viewport.add({
    xtype: 'map',
});

To add map we are using “xtype:map” which is the shortcut of Ext.Map.

There are two main classes in Sencha touch to work with maps functionality.

Ext.Map: This class wraps Google maps in Ext.Component using Google maps api.

Ext.util.Geolocation: This class is used to retrieve location related information like current lat/long, getting lat/long from given address etc.

Another important point is you should include additional JavaScript file in your html to work with Google maps:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

 

Getting current latitude and longitude (geocoding):

To get the current location information we use Ext.util.Geolocation class. Below is the sample code to get the current latitude and longitude.

var currentLocationInfo = Ext.create('Ext.util.Geolocation',{
     autoUpdate:false, // this event continuously fire locationupdate and locationerror event, when to true.
     allowHighAccuracy:false, // setting it to true gives the best accurate result, but consumes more battery and gives slower response.
     listeners:{                                                                            // adding listener
        locationupdate:function(geo){
          var latitude = "Latitude: "+geo.getLatitude(); // will return latitude of current location
          var longitude = "Longitude: "+ geo.getLongitude();  // will return longitude of current location
          var altitude = "Altitude: "+geo.getAltitude(); // will return altitude of current location
          var speed = "Speed: "+geo.getSpeed();  // will return speed of current location
          Ext.Msg.alert("current Info",latitude+"</br>"+longitude+"</br>"+altitude+"</br>"+speed);  // Will display longitude and latitude of current location
        },
        locationerror:function(geo,timeout, permissionDenied, locationUnavailable, message, eOpts){
          if(timeout){  // if location search timed out then display Timeout occurred message
             Ext.Msg.alert('Timeout occurred.');
          } else {  // or else Error occurred
             Ext.Msg.alert('Error occurred’, message);
          }
        }
     }
});

currentLocationInfo.updateLocation();

I have two important methods in above example, one is locationupdate() function which will be called when the current location retrieval is successful. And other is locationerror() function which will be called when location retrieval is failed. LocationUpdate() method return “geo” object, which holds the information about user’s current location.

 

Getting address from current latitude and longitude (Reverse geocoding)

In Sencha touch there is no special mechanism to retrieve address from latitude and longitude. To achieve this you can use Google maps geocoder class, and the process is called reverse geocoding.

Below I have created a method “getAddressFromLatLng(lat, lng)” which will return address from passed latitude and longitude.

function getAddressFromLatLng(lat, lng) {
    var geocoder = new google.maps.Geocoder(); // Geocoder() method will return geocoder object
    var latLng = new google.maps.LatLng(lat, lng); // LatLng() method will return latitude and longitude object which will be used by gecoder object to retrieve address
    geocoder.geocode({
        'latLng': latLng // we are passing latlng to retrieve address, other than that we can pass address object also.
    }, function(results, status) { // callback function of geocode
        if (status == google.maps.GeocoderStatus.OK) { // if status returns ok the display the address
             var msg = "";
             console.log(results);
            if (results[0]) {
                msg = results[0].formatted_address; // will return the formatted address in form of string
            } else {
                msg = "No result found, please modify your search";
        }
        Ext.Msg.alert("Current Location",msg);
        } else {                          // or else display error message
            Ext.Msg.alert("Error ", status);
        }
    });
}

 

Getting latitude and longitude of given location

Previous example showed how to get address from latitude and longitude; you can do vice-versa also, i.e. you can get latitude and longitude values from given address also. Steps are same as we did in previous example, the only difference is instead of passing latlng to geocode() method you should pass address param.

Below is the code snippet to do that:

var geocoder = new google.maps.Geocoder();

var address = "31, Hitech City Road,Silicon Valley, Madhapur, Hyderabad";
geocoder.geocode({ 'address': address }, function(results, status){
   if (status == google.maps.GeocoderStatus.OK) {
      var lat = results[0].geometry.location.lat();
      var lng = results[0].geometry.location.lng();
      console.log("Success!",lat + "," +lng); 
                getAddressFromLatLng(lat,lng);
   }
});

 

displaying mapview

Till now we have only fetched data like getting latitude, longitude, address, speed, current location etc. In this section you will learn how to display that data on mapview.

Below is the code snippet which display map in your application.

var mapObject = Ext.create('Ext.Map',{
    useCurrentLocation: false, // giving center attribute
    mapOptions:{
          backgroundColor:'#000', //background color of map
          center: new google.maps.LatLng (17.451121,78.381902), // map center when map loads initially
           disableDoubleClickZoom:true, // it will disable double tap zoom
           mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP,SATELLITE,TERRAIN,HYBRID
            zoom: 10
      }
});

Ext.Viewport.add(mapObject);

useCurrentLocation: Display current location in the center of map if set to true.

mapOptions: this config is used to set map options like background-color, maytype, initial zoom level etc. For complete list of map options please check google docs.

backgroundColor: background color of map div.

center: map center when map loads initially.

disableDoubleClickZoom: setting it to true will disable the double tap zoom, by default its false.

mapTypeId: use to set maptypes, there are four types of maptype provided by Google maps library

- HYBRID:             displays a transparent layer of streets using satellite images.

- ROADMAP:      display a normal street map.

- SATELLITE:        displays satellite images.

- TERRAIN:          displays terrain on map.

zoom: initial zoom level.

 

Adding Layer

Google map allows to add different type of layer in map. In this section i will only explain about adding different layer to your map. To read more about layer and different options please visit google docs 

  • Traffic

This layer adds current traffic information on map.

Add below script to use traffic layer on map

script:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=weather"></script>

js:

Below is the code to add traffic layer.

Ext.define('mapClass',{
   extend:'Ext.Map',
   config:{
   mapOptions: {
      backgroundColor:'#000',
      center: new google.maps.LatLng (17.451121,78.381902),
      disableDoubleClickZoom:true,
      mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP,SATELLITE,TERRAIN,HYBRID
      zoom: 12
   }
},
  initialize:function(){
    var googleMap = this.getMap();
    var trafficLayer = new google.maps.TrafficLayer();
    trafficLayer.setMap(googleMap);
  }
});
var mapObject = Ext.create('mapClass',{});
Ext.Viewport.add(mapObject);

 

  • Weather and cloud layer

This library adds Weather data and cloud images on map. To display cloud layer on your map, you should set the map zoom level between 0 to 6.

Weather layer displays weather icons on map.

To make it work, add below script:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=weather"></script>
var weatherLayer = new google.maps.weather.WeatherLayer({
   temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});

weatherLayer.setMap(googleMap);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(googleMap);
  • Panoramio Layer

This layer renders a layer of geotagged photos on your map.

To make it work,  add below script:

script:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=panoramio"></script>

js:

var panoramioLayer = new google.maps.panoramio.PanoramioLayer();
panoramioLayer.setMap(googleMap);

 

Displaying markers and adding tap functionality on markers

Markers can be used to identify any location on Google maps, by default marker is displayed as a standard image but can be customized also. In this section you will learn to add markers on your map and display info window on marker tap.

Below is the code which shows how to add markers on map and add tap functionality for markers.

Ext.define('mapClass',{
   extend:'Ext.Map',
   config:{
     mapOptions: {
       backgroundColor:'#000',
       center: new google.maps.LatLng (17.451121,78.381902),
       disableDoubleClickZoom:true,
       mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP,SATELLITE,TERRAIN,HYBRID
       zoom: 12
     }
   },
   initialize:function(){
      var googleMap = this.getMap();
      var marker = new google.maps.Marker({
        animation: google.maps.Animation.BOUNCE, //another type is DROP
        //draggable:true,
        icon:'images/marker.png',
        map: googleMap,
        position: new google.maps.LatLng (17.451121,78.381902)
      });
      var markerTitle = '<p style="font-weight: bold; color:blue">Hitech City, Hyderabad</p>';
      var infowindow = new google.maps.InfoWindow({
        content: markerTitle  // one way to set content of InfoWindow
      });
      google.maps.event.addListener(marker, 'click', function() {
         var position = this.position;
         infowindow.setContent("Latitude: "+position.d+", Longitude: "+position.e); // another way to set content of InfoWindow
         infowindow.open(googleMap,marker);
     });
    //marker.setMap(null); // will remove marker from map
});

var mapObject = Ext.create('mapClass',{});
Ext.Viewport.add(mapObject);

In above code I have created a class called mapClass which extends “Ext.Map” class. Then I have mapOptions config which will be used to configure the map options.

To add markers you should use google.map.Marker(), which will add single marker on map. There are few common fields of marker, below are the names of few of these fields with their description:

animation: defines animation of marker. There are two type of animation, BOUNCE: bounce the marker continuously, DROP: drops the marker from top.

draggable: makes the marker draggable if set to true.

icon: displays customized marker image instead of default standard image.

map: map object on which marker should be placed.

position: latitude/longitude position of marker on map.

next step is to add click functionality of marker. To do that you should add listeners on Google map to trigger an event.

google.maps.event.addListener(marker, 'click', function() {
   var position = this.position;
   infowindow.setContent("Latitude: "+position.d+", Longitude: "+position.e);
   infowindow.open(googleMap,marker);
});

This code snippet will add click event to marker, in callback function I am displaying infoWindow.

infoWindow is responsible to display the content on map in popup window. There are two ways to set its content:

1) Set the content while creating its object.

2) Use setContent() method to set the its content.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>