0

I'm working on a program that is supposed to display a map with java swing using a google maps api url by given coordinates, my problem is that when i run the code i get this exception:

java.io.IOException: Server returned HTTP response code: 403 for URL

This is my code

public class GoogleMapsDem {
    public static void main(String[] args) throws IOException {

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

        try {
            String latitude = "40.714728";
            String longitude = "-73.998672";

            String imageUrl = "https://maps.googleapis.com/maps/api/staticmap?center=" +
                    latitude +
                    "," +
                    longitude +
                    "&zoom=11&size=612x612&scale=2&maptype=roadmap&key=YOUR_API_KEY";
            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);
            }

            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // create a GUI component that loads the image: image.jpg
        //
        ImageIcon imageIcon = new ImageIcon((new ImageIcon("image.jpg"))
                .getImage().getScaledInstance(630, 600,
                        java.awt.Image.SCALE_SMOOTH));
        test.add(new JLabel(imageIcon));

        // show the GUI window
        test.setVisible(true);
        test.pack();
    }
}

What could be causing this?

Yrll
  • 1,619
  • 2
  • 5
  • 19
  • Make sure you have enabled "Static Maps API" service in addition to "Google Maps API". https://stackoverflow.com/questions/19408066/the-google-maps-api-server-rejected-your-request – Vasim Hayat Dec 19 '21 at 04:33
  • 1
    It looks like you've included your google maps API key – you may want to reset that, since it's now public and bad actors may steal it. – Alan Dec 20 '21 at 17:52

1 Answers1

1

The status code 403 Forbidden represents a client error, which means that the server has the ability to process the request but refuses to authorize access. Simply put, you do not have permission to access this url

wudskq
  • 11
  • 2