Using Google Maps API in Appery.io App
Google Maps is probably the most popular map widget used in the mobile apps today. Working with Google Maps in Appery.io app builder is very easy but as the same time is not very different than using other dev. tools. To add a Map component, simply drag and drop it from the palette onto the page:
Rename the Map component to google_map. This is done so it’s simpler to reference the component from code.
Next you can create your own JavaScript class and define map variable as following:
var map; function initialize() { map = Apperyio("google_map").gmap; if (!map) { setDelay(); } else { directionsDisplay = new google.maps.DirectionsRenderer(); } } function setDelay() { setTimeout(initialize, 50); }
Google Maps is usually loaded asynchronously, so the approach with delay (as mentioned in code above) can be handy. This will ensure the map is completely loaded before you try to use it.
Generally that’s all you need to use Google Maps JavaScript API. All the actions you want to do next you can make based on Google Maps JavaScript API. Lets say you want to show direction from point A to point B. Place the button on the page and run following JavaScript by clicking on it:
var directionsDisplay = new google.maps.DirectionsRenderer(); var directionsService = new google.maps.DirectionsService(); var request = { origin: 'Los Angeles', destination: 'San Francisco', travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(response, status) { directionsDisplay.setMap(map); if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } else { alert("Directions query unsuccessful. Response status: " + status); } });
The directions will be shown on the map:
To place the marker on the map you should provide latitude and longitude values of a certain point. Try to run following JavaScript code and you’ll see how the marker drop on the map:
var markerLatLng = new google.maps.LatLng(37.913597,-122.066059); var marker = new google.maps.Marker({ position: markerLatLng, map: map, title: "Walnut Creek, CA", animation: google.maps.Animation.DROP });
You can also place markers based on geographical names, not latitude and longitude. In this case you should use Google Geocoding services, to convert user-friendly names to latitude and longitude values. Create a REST service in the app builder with the following URL:
https://maps.googleapis.com/maps/api/geocode/json
You’ll get a coordinates (latitude/longitude) as a response of this service, and you of course can use them to add markers.
Any layers provided by Google Maps can be added too. Here is an example for Traffic layer, just run this code by clicking on the button:
var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map);
As you can see using Google Maps and its API is very straightforward in Appery.io app builder. Check out our Google Maps section for more detailed tutorials.