I am unable to access the Google API due to the restrictions set in the Access-Control-Allow-Origin header, even though I have specified dataType as

My attempts to utilize Google's Places API in order to retrieve nearby locations have hit a roadblock. I initially tried adding the header exactly as outlined in the code, but it proved ineffective. Subsequently, I experimented with dataType:'jsonp', however, this approach resulted in some errors. Upon examining the error within Chrome, I noticed that the data was successfully returned from Google, yet I encountered issues accessing it. Interestingly, Firefox presented only the second line of the data "html_attributions":[]," instead of displaying the entire dataset.

$.ajax({                        
       url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=13.089500428429146,77.48688038438559&radius=1000&type=bus_station&key=AXXXXXXXXXXXXXXXXXXXXXXX",
        type:"GET",
        //headers:{"Access-Control-Allow-Origin":"https://maps.googleapis.com/"},
        dataType: 'jsonp',
        success: function (return_data_json){
                console.log(return_data_json);
        }   
});

Answer №1

Here's how we can implement this in Javascript - Google offers its own functions for this purpose.

Link: https://developers.google.com/maps/documentation/javascript/places#place_search_requests

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '500',
    types: ['store']
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}
  • If anyone wants to access the place Id and other information, here is how it can be done. In the callback function, we have the JSONArray of places returned by Google. Inside the for loop of the callback function after the line var place = results[i];, you can retrieve what you need like

    console.log(place.name);
    console.log(place.place_id);
    var types = String(place.types);
    types=types.split(",");
    console.log(types[0]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am in need of a efficient loader for a slow-loading page on my website. Any recommendations on where to find one that works

I'm experiencing slow loading times on my website and I'm looking to implement a loader that will hide the page until all elements are fully loaded. I've tested several loaders, but they all seem to briefly display the page before the loader ...

Enhance your figures with a unique Javascript magnifying tool that works seamlessly across all browsers

After searching the web for magnifying glasses, I found that most only work for one picture. So, I took matters into my own hands and created a magnifying glass that can magnify all pictures within a specific div. It functions perfectly on Chrome browser b ...

"What is the best way to use JavaScript to dynamically modify the hover color of a button

I am looking to customize the hover color of all buttons on my website to align with the overall theme. The challenge is that I need the hover color to vary based on the page it originates from. I have successfully identified the referring page, but I am s ...

Is there a way to determine if a container is overflowing at the top?

Currently, I am using Puppeteer to scrape Slack. My goal is to confirm whether I have scrolled to the very top of the channel feed. The issue arises because the channel feed does not actually scroll, making it impossible for me to utilize the method outli ...

Testing AJAX functionality in WordPress resulting in a 400 error code

After following a straightforward tutorial to understand AJAX calls in WordPress, I have gathered all the necessary code snippets: Inside functions.php add_action( 'admin_enqueue_scripts', 'my_enqueue' ); function my_enqueue() { ...

Encountering a TypeError when using the react useRef() hook

During my work on an app utilizing the webRTC API and working with the useRef() hook in React, I encountered an error Error: TypeError: myVideo.current is undefined ContextProvider SocketContext.js:27 promise callback*ContextProvider/< SocketCon ...

Using Javascript Regular Expressions to validate that the first number in an amount is non-zero

Need a solution to only accept numbers that do not start with zero, but can contain zeros after the first digit. Currently using var.replace(/[^1-9]/g, ''); which prevents input of 0 altogether. Examples of valid inputs: 10 9990 Examples of in ...

Why isn't the login redirect script working without any errors or redirection?

Struggling to develop a Greasemonkey script that can automatically fill in certain forms and then redirect to another URL once the form is submitted. // ==UserScript== // @name usersaime // @description fills data form for user and pass // @include h ...

The sequence in which functions are executed when bound to an event in JavaScript

Recently, I found myself diving into the world of JavaScript to uncover details about how functions bound to a page event are executed. Take, for instance, when using an EventListener. Let's say you bind three functions - A(), B(), and C() - to the s ...

Show the JSON response from the controller on the view page

In my controller, I have a JsonResult action that returns a list of House objects. My goal is to retrieve this data onclick using ajax and display the JSON data within my view. While I can see the proper response and JSON result in Firebug, I'm not su ...

How to modify the background color in Material Ui's datepicker?

Is there a way to customize the background color of my Material UI datepicker modal? To change the colors, you can use the createMuiTheme function from "@material-ui/core": const materialTheme = createMuiTheme({ overrides: { MuiPickersToolbar: ...

Tips for updating the color of a table row when it is chosen and a row is inserted using ajax

I have successfully added table rows dynamically through ajax in MVC C#. Now, I am looking to change the color of a selected row. This effect works well on the table with rows generated in the HTML view. <div class="col-lg-6 col-sm-12"> ...

What is the optimal approach: Extracting HTML from a jQuery response?

Just wondering how people handle this situation...if a user adds something to a list and, when it's done, triggers the following ajax code to update the .user-stream-list $.ajax({ url: "user-stream-list.php", success: function(data){ ...

Using Vuetify 3 to conditionally render v-icon inside a v-data-table

I am struggling to display a v-icon conditionally in a v-data-table within Vuetify 3, based on a value of either 1 or 0. In Vuetify 2, there were multiple easy ways to achieve this, but it's not rendering in the latest version. I want to show v-icons ...

Achieving Ajax Request Activation through Button Click in Bootstrap

I am currently working on a modal form using Bootstrap that allows users to customize a specific item before adding it to the cart. My issue is that the "Add to Cart" button does not trigger the Ajax request as intended. I have followed a modified version ...

My div is currently being concealed by a jQuery script that is hiding all of its

Below is the current code snippet: jQuery(document).ready(function($) { $("ul.accordion-section-content li[id*='layers-builder'] button.add-new-widget").click(function() { $("#available-widgets-list div:not([id*='layers-widget']) ...

Navigate to the following section on an HTML page by clicking a button using jQuery

Within my application using Jquery / Javascript, I am looking to implement a specific functionality. I currently have several div elements like the ones below: <div id="div1"></div> <div id="div2"></div> <div id="div3"></ ...

The functionality of Angular.js ajax and apply is experiencing technical difficulties

As I venture into the world of angular.js, I am facing a challenge with displaying the correct content on my website. The pages' content is fetched via AJAX (currently from static data, but eventually from a database). When I place a block with the ng ...

Is it possible to retrieve a callback function from a select event in the Bootstrap dual listbox?

I'm fairly new to front-end development and have been using the Bootstrap DualListbox for a project. I'm looking for a way to save items moved from one list to another to a database before they are officially transferred. Is there a callback func ...

Customize the jQuery datepicker by assigning a class to the first 17 days

How can I apply a class to only the first 17 days on a jquery datepicker calendar? I've attempted the following code, but it ends up adding the class to every day... beforeShowDay: function(date) { for (i = 0; i < 17; i++) { return [t ...