📜 ⬆️ ⬇️

Google Maps on iPhone without GoogleSDK

Google maps for iPhone came out quite recently, and it's not so easy to get an API key for the SDK. Maybe the method outlined here will seem commonplace to many, but still I will write.

The main idea - the use of JavaScript API. For example, I chose the Direction API.
2 input fields for “from” and “to” and “WebView” are created to display the result.

image

I set the template for displaying in WebView in a separate file, called it “map.html”. Here are its contents:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map_canvas { height: 100% } </style> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script> <script type="text/javascript"> var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var map; function initialize() { directionsDisplay = new google.maps.DirectionsRenderer(); var chicago = new google.maps.LatLng(41.850033, -87.6500523); var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago } map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); directionsDisplay.setMap(map); calcRoute('chicago, il', 'st louis, mo'); } function calcRoute(start, end) { var request = { origin:start, destination:end, travelMode: google.maps.TravelMode.DRIVING }; directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); } }); } </script> </head> <body onload="initialize()"> <div id="map_canvas" style="width:100%; height:100%"></div> </body> </html> 

')
Then everything is very simple. In "viewDidLoad", a "createMap" is called to initialize the map. “CreateMap” code:

 - (void) createMap:(id)sender{ [map loadHTMLString:[self readFile:[[NSBundle mainBundle] pathForResource:@"map" ofType:@"html"]] baseURL:[NSURL URLWithString:@"google.com"]]; } 


And the handler is set to change the “to” field:

 - (void) findOnMap:(id)sender{ [map stringByEvaluatingJavaScriptFromString: [[[[@"calcRoute('" stringByAppendingString: from.text ] stringByAppendingString: @"', '"] stringByAppendingString: to.text] stringByAppendingString: @"');" ] ]; } 


Thus, you can perform any API request to GoogleMaps. This, of course, is a temporary method until Google starts to issue keys to the SDK immediately upon request.

Here's what it looks like:

Source: https://habr.com/ru/post/165461/


All Articles