Remove markers from Google Maps when there are no markers present

I am working on a mobile web app that features a mapping page where users can toggle different POI's, such as Gas Stations. The issue I am facing is when the google.maps.places.PlacesService does not find any Gas Stations within my specified radius, I struggle to revert the CSS changes for toggling off. I'm unsure of where or how to implement a condition for handling this scenario when the marker set returns empty. Should it be in the clearMarkers function or somewhere else?

//Gas
var gas_markers = null;
function gas() {
if (gas_markers === null) {
    document.getElementById('gas').style.backgroundColor = "rgb(175,175,175)";
    document.getElementById('gas').style.borderColor = "black";
    document.getElementById('gas').style.color = "rgb(75,75,75)";

    var request = {
        location: arena,
        radius: 3500,
        type: ["gas_station"]
    };
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);


    function callback(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            if (gas_markers === null) gas_markers = [];
            for (var i = 0; i < results.length; i++) {
                createMarker(results[i]);
            }
        } else {
            clearMarkers();
        }
    }

    function createMarker(place) {
        var placeLoc = place.geometry.location;
        var gas_marker = new MarkerWithLabel({
            position: place.geometry.location,
            draggable: false,
            raiseOnDrag: false,
            map: map,
            icon: "images/gas1.png",
            labelContent: "",
            labelAnchor: new google.maps.Point(10, 0),
            labelClass: "pin", 
            labelStyle: {
                opacity: 0.95
            }
        });
        gas_markers.push(gas_marker);
        var infowindow = new google.maps.InfoWindow();

        google.maps.event.addListener(gas_marker, 'click', function () {
            infowindow.setContent('Promo Code: <br> Gas');
            infowindow.open(map, this);
        });
    }

} else {

    clearMarkers();
    document.getElementById('gas').style.backgroundColor = "rgb(75,75,75)";
    document.getElementById('gas').style.borderColor = "gray";
    document.getElementById('gas').style.color = "rgb(175,175,175)";

    gas_markers = null;

}

function clearMarkers() {

    for (var i = 0; i < gas_markers.length; i++) {
        gas_markers[i].setMap(null);
    }
    gas_markers = [];
}

}
 //End of Gas function

When the request returns no results and gas_markers becomes null, it exits the IF statement making it difficult to toggle off. Any assistance on how to handle this situation would be greatly appreciated. Thank you.

Answer №1

Ensure that gas_markers is always treated as an array. If it contains existing markers (length > 0) and new ones are being added, clear out the old ones.

Check out this proof of concept code snippet:

var map = null;

function initialize() {
  var mapOptions = {
    zoom: 6,
    center: new google.maps.LatLng(47.606209, -122.332069)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  arena = map.getCenter();
  google.maps.event.addListener(map, 'center_changed', function() {
    arena = map.getCenter();
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

//Gas
var gas_markers = [];
var arena = null;

function gas() {
  if (gas_markers.length > 0) {
    clearMarkers();

    document.getElementById('gas').style.backgroundColor = "rgb(75,75,75)";
    document.getElementById('gas').style.borderColor = "gray";
    document.getElementById('gas').style.color = "rgb(175,175,175)";
  }
  var request = {
    location: arena,
    radius: 3500,
    type: ["gas_station"]
  };
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);


  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      document.getElementById('gas').style.backgroundColor = "rgb(175,175,175)";
      document.getElementById('gas').style.borderColor = "black";
      document.getElementById('gas').style.color = "rgb(75,75,75)";


      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
    }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var gas_marker = new MarkerWithLabel({
      position: place.geometry.location,
      draggable: false,
      raiseOnDrag: false,
      map: map,
      labelContent: "",
      labelAnchor: new google.maps.Point(10, 0),
      labelClass: "pin",
      labelStyle: {
        opacity: 0.95
      }
    });
    gas_markers.push(gas_marker);
    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(gas_marker, 'click', function() {
      infowindow.setContent('Promo Code: <br> Gas');
      infowindow.open(map, this);
    });
  }

  google.maps.event.addDomListener(document.getElementById('clear'), 'click', clearMarkers);

  function clearMarkers() {
    for (var i = 0; i < gas_markers.length; i++) {
      gas_markers[i].setMap(null);
    }
    gas_markers = [];

    document.getElementById('gas').style.backgroundColor = "rgb(75,75,75)";
    document.getElementById('gas').style.borderColor = "gray";
    document.getElementById('gas').style.color = "rgb(175,175,175)";
  }

}
html,body,#map-canvas {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/markerwithlabel.js"></script>
<div id="gas"> </div>
<input type="button" onclick="gas()" value="gas" />
<input type="button" id="clear" value="clear" />
<div id="map-canvas"></div>

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

Is per-page localStorage the solution?

Can a local storage be created in HTML5 that is only accessible to a single webpage? I am currently exploring the potential of creating self-contained single-page applications and whether users can host them themselves, for example on Dropbox (which offer ...

Unlocking a targeted list in AngularJS

I have the following code snippet that I am using to implement ng-repeat in an Angular project. My goal is to display only the list item that I click on, but currently, when I click on the symbol ~, it displays all the lists. Is there a way to specify cer ...

Javascript - The art of accessing an anonymous array

I'm trying to extract data from an API, but I've run into a snag. There's a list without a name attached to it, making it impossible for me to access the values inside. Here's a simplified example of what I mean: (Here is the JSON stru ...

Arrangement of divs to showcase Background images

Apologies in advance for any errors in my code or question, as I am still learning about coding. Please forgive the spacing in links and lack of correct use of characters - < - I'm having some trouble posting code :) I am working on a website call ...

ReactJS safeguarded route redirection/refresh obstacle

Utilizing react and react-router-dom: import React from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; To secure a route with the following: Router const Router = () => { return ( <Switch> ...

Webpack compilation results in missing SVG icons display

As a newbie in web application development, I find myself in the final stages of my project. My current challenge involves bundling the entire project using webpack, and it's mostly smooth sailing except for one hiccup with my SVG icons. The issue se ...

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

Unit testing promises in Angular using Jasmine

My goal is to create a unit test that demonstrates the process of combining two promises using $q.all in Angular, and then confirming that both promises are resolved simultaneously. describe("Application controller", function() { var scope; var ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

Continuous animation for a sequence of overlapping images with smooth transitions

Currently, I am in the process of developing a JavaScript script that will cycle through a series of images within the same <div>. The goal is to create a seamless animation effect with the image transitions. Although the images are cycling through, ...

Tips for fixing the issue of "The use of getPreventDefault() is outdated. Please use defaultPrevented instead."

When attempting to fetch data for a specific user from an SQL Server database using JSON data, I encountered an error message in the console: "Use of getPreventDefault() is deprecated. Use defaultPrevented instead." Additionally, the values are not bei ...

Learn how to design a div with an arrow pointing upwards that contains content. Utilize HTML and CSS to create this unique visual element. Each arrow should have a hover effect that only activates when hovering over

I attempted this previously with just an arrow image, but due to the rectangular shape of the div section, the area without the arrow remains hoverable. Is there a method to customize the div to mirror the image below, ensuring that only the arrow is clic ...

Is it possible to manipulate the position of a Three.js model using a

Currently, I am reviewing the three.js documentation and have come across the controls section. I have noticed that orbit can be used to control the camera's view of the scene, and I have verified that it is compatible with touchscreens. However, one ...

Enhance website security with X-ray standard user agent

Currently working on a Node.js application and utilizing the X-Ray library along with Request-X-Ray as a driver. I am curious to find out which user-agent X-Ray uses by default. Can anyone provide insights on this? ...

React's Dynamic Table fails to rerender when updated values are placed in the same row and under the same header

Here is the table generated by my functional component: <table class="table"> {/* Consonant Table */} <tr> <th colSpan="2">---</th> {headersPOA. ...

Tips for implementing two functions to run within the onClick event handler in React

I am looking to simultaneously execute two functions handleClose and saveData within the onClick method. The specific location where I want this execution to happen: <Button variant="contained" onClick={saveData}&g ...

Passing Data Between Page and Component (NEXT.JS + LEAFLET Integration)

I have recently started using Next.js with Leaflet maps and have encountered a beginner's question. I created a page in Next.js ( /pages/map/[id].jsx ) that utilizes a component ( /component/Map.jsx ). Within the page ( [id].jsx ), I fetch a JSON fil ...

Calculating the median in JavaScript utilizing a for loop

Currently, I am in the process of learning JavaScript. My goal is to calculate the median of a set of numbers that I input through a prompt when I click the button labeled "find median". function CalculateMedia() { var n = prompt("Enter the number of e ...

PayPal's Intelligent Payment Buttons: Oops! There seems to be an issue with parsing the JSON data - an unexpected character was found at line 1,

I've been racking my brain over this issue for the past two days... I've been attempting to integrate Smart Payment Buttons from PayPal, diligently following each step in the guide. However, I keep encountering the following error: Error: JSON. ...

What is the method for configuring a timezone in Selenium Chromedriver?

I'm struggling to set a specific timezone while using Chromedriver. Is there an argument in ChromeOptions that can help with this? The problem arises when I visit certain websites (such as ), where it displays the system time based on Windows setting ...