R.Karthik Vasishta
R.Karthik Vasishta

Reputation: 91

How to access google maps api in Java Application?

How do you access google maps API from a Java application?

Upvotes: 9

Views: 10876

Answers (5)

Eugene Maysyuk
Eugene Maysyuk

Reputation: 3378

You can use official Java Client for Google Maps

    <dependency>
        <groupId>com.google.maps</groupId>
        <artifactId>google-maps-services</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.25</version>
    </dependency>

Here's an example how to access Google Maps Places API

public static List<PlacesSearchResult> nearbySearch(double lat, double lng, int radiusInMeters) {
    List<PlacesSearchResult> results = new ArrayList<>();
    try {
        GeoApiContext ctx = new GeoApiContext.Builder().apiKey(API_KEY).build();
        PlacesSearchResponse response = PlacesApi.nearbySearchQuery(ctx, new LatLng(lat, lng))
            .type(PlaceType.RESTAURANT)
            .radius(radiusInMeters)
            .await();

        results.addAll(Arrays.asList(response.results));

        int page = 1; // Google Maps API provides maximum 60 results by search (3 pages maximum, each containing 20 records)
        while (response.nextPageToken != null && !response.nextPageToken.isBlank() && response.results.length == 20 && page <= 2) {
            Thread.sleep(3000); // Google has SLA for no more than N requests per second in free tier
            response = PlacesApi.nearbySearchNextPage(ctx, response.nextPageToken).await();
            results.addAll(Arrays.asList(response.results));
            page++;
            Thread.sleep(2000);
        }

    } catch (ApiException e) {
        logger.error("ApiException: ", e);
    } catch (InterruptedException e) {
        logger.error("InterruptedException: ", e);
    } catch (IOException e) {
        logger.error("IOException: ", e);
    }

    return results;
}

for findPlace

public static PlacesSearchResult[] findPlace(double lat, double lng) {
    GeoApiContext ctx = new GeoApiContext.Builder().apiKey(API_KEY).build();

    FindPlaceFromText response = null;
    try {
        response = PlacesApi.findPlaceFromText(ctx, "restaurants", FindPlaceFromTextRequest.InputType.TEXT_QUERY)
            .fields(
                FindPlaceFromTextRequest.FieldMask.NAME,
                FindPlaceFromTextRequest.FieldMask.FORMATTED_ADDRESS,
                FindPlaceFromTextRequest.FieldMask.RATING,
                FindPlaceFromTextRequest.FieldMask.OPENING_HOURS)
            .locationBias(new FindPlaceFromTextRequest.LocationBiasCircular(new LatLng(lat, lng), 10000))
            .await();
    } catch (ApiException e) {
        logger.error("ApiException: ", e);
    } catch (InterruptedException e) {
        logger.error("InterruptedException: ", e);
    } catch (IOException e) {
        logger.error("IOException: ", e);
    }
    
    return response != null ? response.candidates : null;
}

Upvotes: 0

Mohamed Mansour
Mohamed Mansour

Reputation: 40149

you can use Swing Labs, JXMapKit from swingx: http://today.java.net/pub/a/today/2007/10/30/building-maps-into-swing-app-with-jxmapviewer.html

It is pretty straight forward. For more info refer to the website.

JXMapKit mapView = new JXMapKit();
mapView.setDefaultProvider(DefaultProviders.OpenStreetMaps);
mapView.setDataProviderCreditShown(true);
add(mapView)

It will look like this:

alt text
(source: java.net)

Take a look at the source code in the article above, with three lines of code, you can view a map easily:

Upvotes: 1

Joshua Smith
Joshua Smith

Reputation: 89

if you are looking for just a static map the you can use this code to get the map working:

import java.awt.BorderLayout;

public class GoogleMapsGui extends JFrame {

    final Logger log = Logger.getLogger(GoogleMapsGui.class.getName());
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GoogleMapsGui frame = new GoogleMapsGui();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GoogleMapsGui() {
        setTitle("Map");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 592, 352);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JFrame test = new JFrame("Google Maps");

        try {
            // String latitude = "-25.9994652";
            // String longitude = "28.3112051";
            String location = JOptionPane
                    .showInputDialog(" please enter the desired loccation");// get
                                                                            // the
                                                                            // location
                                                                            // for
                                                                            // geo
                                                                            // coding
            Scanner sc = new Scanner(location);
            Scanner sc2 = new Scanner(location);
            String marker = "";
            String path = JOptionPane
                    .showInputDialog("what is your destination?");
            String zoom = JOptionPane
                    .showInputDialog("how far in do you want to zoom?\n"
                            + "12(zoomed out) - 20 (zoomed in)");

            String imageUrl = "https://maps.googleapis.com/maps/api/staticmap?";
            while (sc.hasNext()) {// add location to imageUrl
                imageUrl = imageUrl + sc.next();
            }
            marker = "&markers=color:red|";
            while (sc2.hasNext()) {// add marker location to marker
                marker = marker + sc2.next() + ",";

            }
            marker = marker.substring(0, marker.length() - 1);

            imageUrl = imageUrl + "&size=620x620&scale=2&maptype=hybrid"
                    + marker;
            //
            log.info("Generated url");

            String destinationFile = "image.jpg";

            // read the map image from Google
            // then save it to a local file: image.jpg
            //
            URL url = new URL(imageUrl);
            InputStream is = url.openStream();
            OutputStream os = new FileOutputStream(destinationFile);

            byte[] b = new byte[2048];
            int length;

            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }
            log.info("Created image.jpg");

            is.close();
            os.close();
            sc.close();
            sc2.close();
            log.info("Closed util's");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
            log.severe("Could not create image.jpg");
        }// fin getting and storing image

        ImageIcon imageIcon = new ImageIcon((new ImageIcon("image.jpg"))
                .getImage().getScaledInstance(630, 600,
                        java.awt.Image.SCALE_SMOOTH));
        contentPane.setLayout(null);
        JLabel imgMap = new JLabel(imageIcon);
        imgMap.setBounds(5, 5, 571, 308);
        contentPane.add(imgMap);
    }

}

also check out the Goolge static maps API here

Upvotes: 0

adrian.tarau
adrian.tarau

Reputation: 3154

You can use Swing-WS, a component JXMapViewer is available and provides similar functionality as JavaScript version. However it is still not legal to access Google tile servers outside the provided APIs : JavaScript and Flash.

There is an issue opened to track this request : http://code.google.com/p/gmaps-api-issues/issues/detail?id=1396. It is approved but who knows when it's gonna be available.

Upvotes: 3

jsight
jsight

Reputation: 28409

Your best bet for client side Java would be the Static Maps API. For server-side Java, the answer will heavily depend on what framework you are using for development. Having said that, the Google Maps API is well documented.

Upvotes: 2

Related Questions