Having trouble changing the icon in Google Maps during the event?

Seeking guidance with Google API V3 as a newcomer. The task at hand is to switch the icon during a zoom event. Everything works smoothly except for the part where I need to detect the change in zoom and modify the icon from a basic circle to Google's standard red icon. Any suggestions or corrections are greatly appreciated, thank you.

<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
  var infowindow;
  var map;
  function initialize() {
    var myLatlng = new google.maps.LatLng(20, 0);
    var myOptions = {
    zoom: 3,
    panControl:true,
    zoomControl:true,
    mapTypeControl:true,
    scaleControl:true,
    streetViewControl:true,
    overviewMapControl:true,
    rotateControl:true,    
    center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
 }
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("worldcities.xml", function(data) {
  var markers = data.documentElement.getElementsByTagName("marker");
  for (var i = 0; i < markers.length; i++) {
    var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
                                parseFloat(markers[i].getAttribute("lng")));
var circleOptions = {
    strokeColor: '#FF0000',
    strokeOpacity: 0.65,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.25,
    map: map,
    center: latlng,
    radius: parseInt(markers[i].getAttribute("population"))/25
    };

    var marker = createMarker(markers[i].getAttribute("name"), latlng,         markers[i].getAttribute("population"), markers[i].getAttribute("countrycode"), markers[i].getAttribute("region"));
var onekmcircle = new google.maps.Circle(circleOptions);
}
 });
}

function createMarker(name, latlng, popl, cntry, rgon) {
    var marker = new google.maps.Marker({
position: latlng, 
map: map,
icon: {
    path: google.maps.SymbolPath.CIRCLE,
scale: 2

    }, 
title: name});
var contentstring = '<b>'+name+'</b>'+'<br>Population: '+popl+'<br>Country: '+cntry+'<br>Region: '+rgon;


google.maps.event.addListener(marker, "click", function() {
  if (infowindow) infowindow.close();
  infowindow = new google.maps.InfoWindow({content: contentstring});
  infowindow.open(map, marker);
  var zoomLevel = map.getZoom();
  map.setCenter(marker.getPosition());
  if (zoomLevel<6)
{
    map.setZoom(6);

}

});



return marker;
}

google.maps.event.addListener(map, 'zoom_changed', function() {

var url ='http://maps.google.com/mapfiles/ms/icons/red-dot.png';
var icon = google.maps.MarkerImage(url);
var currentZoom = map.getZoom();
  if (currentZoom >9){
for(i=0; i< markers.length; i++ ) {
    markers[i].setIcon(icon);

   }
}
});

Answer №1

Great news! I have successfully corrected your code for you, addressing the errors that were present. One major issue was that you were not storing the markers in an array to be looped through by the event listener.

To resolve this, I introduced the gMarkers array and tested the revised code on your website. Everything appears to be functioning as expected. Feel free to reach out if you require further clarification or assistance.

 var infowindow;
 var map;
 var gMarkers=[];

  function initialize() {
    var myLatlng = new google.maps.LatLng(20, 0);
    var myOptions = {
        zoom: 3,
        panControl:true,
        zoomControl:true,
        mapTypeControl:true,
        scaleControl:true,
        streetViewControl:true,
        overviewMapControl:true,
        rotateControl:true,    
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    downloadUrl("worldcities.xml", function(data) {
        markers = data.documentElement.getElementsByTagName("marker");
    });

    for (var i = 0; i < markers.length; i++) {
        var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
        var circleOptions = {
            strokeColor: '#FF0000',
            strokeOpacity: 0.65,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.25,
            map: map,
            center: latlng,
            radius: parseInt(markers[i].getAttribute("population"))/25
        };

        gMarkers.push(createMarker(markers[i].getAttribute("name"), latlng,markers[i].getAttribute("population"), markers[i].getAttribute("countrycode"), markers[i].getAttribute("region")));
        var onekmcircle = new google.maps.Circle(circleOptions);    
    }


    google.maps.event.addListener(map, 'zoom_changed', function() {
        var url ='http://maps.google.com/mapfiles/ms/icons/red-dot.png';
        var icon = google.maps.MarkerImage(url);
        var currentZoom = map.getZoom();
          if (currentZoom >9){
            for(var i=0; i< gMarkers.length; i++ ) {
                gMarkers[i].setIcon(icon);
            }
          }else{
                for(var i=0; i< gMarkers.length; i++ ) {
                    gMarkers[i].setIcon({path: google.maps.SymbolPath.CIRCLE,scale: 2});
                }
          }
    });

 }

function createMarker(name, latlng, popl, cntry, rgon) {
    marker = new google.maps.Marker({
        position: latlng, 
        map: map,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 2

        }, 
        title: name
    });

    var contentstring = '<b>'+name+'</b>'+'<br>Population: '+popl+'<br>Country: '+cntry+'<br>Region: '+rgon;

    google.maps.event.addListener(marker, "click", function() {
        if (infowindow) infowindow.close();
        infowindow = new google.maps.InfoWindow({content: contentstring});
        infowindow.open(map, marker);
        var zoomLevel = map.getZoom();
        map.setCenter(marker.getPosition());
        if (zoomLevel<6){
            map.setZoom(6);
        }
    });

    return marker;
}

Answer №2

google.maps.event.addListener(marker,\'mouseover\', function() {
    marker.setIcon("fileadmin/new_templates/images/home_map_notification_hover.png");
    $.ajax({
    type: "POST",
    async : false,
    data: \'address=\'+add ,
    success: function(html){

            infowindow.setContent(html); 
            infowindow.open(map,marker);
        },
    });
});
// Handling Mouse out event
google.maps.event.addListener(infowindow, \'mouseout\', function () {
marker.setIcon("fileadmin/new_templates/images/home_page_map_notification.png");
});
// Handling Infowindow close event
google.maps.event.addListener(infowindow, \'closeclick\', function () {
marker.setIcon("fileadmin/new_templates/images/home_page_map_notification.png");
});

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

"Utilize Regular Expressions to conceal part of a text string with a

Looking for a way to conceal part of a string using JavaScript? For example, wanting to mask the second and third segments of a credit card number like this using regex: 4567 6365 7987 3783 → 4567 **** **** 3783 3457 732837 82372 → 3457 ****** 82372 ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Pull data from database to populate spinner, then extract the chosen spinner value and store it in a SQL database

Currently in the process of developing a bus location application that pulls data from a database to populate a spinner. However, encountering an issue when attempting to retrieve the selected value from the spinner, resulting in the app crashing. The goal ...

Messaging Mishap with GCM

Here is a demo of GCM that works: If you refresh the page, you will notice a new random number. Only 25% of page refreshes actually send a message to GCM. Is this behavior normal or can I make some tweaks to the code to improve it? The page does not have ...

Issue: When attempting to invoke a @Composable function within a lambda function, it is important to ensure that this is done within the context of another @Composable function

I'm struggling to include a @Composable function within another function, but I keep encountering the error message saying "@Composable invocations can only happen from the context of a @Composable function". I've tried looking for solutions onli ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. After inspecting each number, it was revealed that .MuiMenuItem-root ...

Get the QR code canvas image with a customized background by downloading it

I am having trouble with downloading a QR code canvas image with a background. The download works fine, but my device is unable to scan the code properly due to an incomplete border. I need to add a white background behind it to make it larger. Current im ...

Subtracting 25% from the width of the web browser

After spending some time trying to solve this issue by myself, I've decided to reach out for help here where I know I can get some great responses. I am looking to determine the dimensions of the browser window minus 25%. Specifically, I have a two-c ...

How can I send dynamic props between pages using Next.js?

I am currently exploring Next.js and attempting to create a page (index.js) that fetches data about different countries and then displays this information. I would like each country element displayed on the page to have a button that leads to another page ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

What is the best method for locating the innermost element of an HTML tree that has a specific class assigned

I am working on a project that involves a menu system. One of the features I am implementing is that when a tree within the menu is opened, it receives the "active" class. My goal now is to dynamically retrieve the deepest sub-menu within this structure ...

Changing the URL dynamically based on user interaction with jQueryLet's leverage the power of

In continuation to my previous post, I am looking to dynamically change a URL based on the selected language. For example, if the current URL is href="../folder/Languages/English/test/test.html, clicking or selecting another language should update it to: h ...

Retrieving data from external JSON files

I implemented this JavaScript code to retrieve JSON data from an external server. The JSON data gets loaded from the server, but I'm unsure how to extract markers from the Google Map using this external JSON data. var map, infowindow; //// // Fet ...

Trouble encountered while setting up Firebase Auth for React Native by utilizing AsyncStorage

Trying to implement SMS authentication via Firebase has presented some challenges for me. Despite poring over the documentation and scouring Google for solutions, I've hit a dead end. My setup is pretty basic - just a single input field and a "Send" b ...

How to toggle the visibility of an element in an array using AngularJS and JavaScript

Is there a way to show additional information when an item in ng-repeat is clicked, and then hide this extra info when the mouse leaves that same item? One issue I am facing with the code snippet below is that when a user clicks on a different item, it al ...

JavaScript allows for the insertion of values into either a textbox or dropdown menu

Is there a way to restrict the client from inserting both of these fields: either selecting from a textbox (selected Column) or choosing a value from a dropdown menu (selected Column), but only one field is allowed in a gridview? <asp:GridView ID="gvMe ...

How to switch between classes for elements and return to the original one when none of the elements is chosen

Hello there, I need some assistance. Here's the scenario: I am working with a grid of six items. My goal is to have the first item in the grid become active by default. When the user hovers over any of the remaining five items, I want the active clas ...

Encountering difficulties with updating an object in Angular

Currently, I have the ability to generate objects and store them in a rails database using a json api. The application is a basic todo list where adding an object places it into the todo list above the input fields. Furthermore, I can access all objects on ...

Can you explain how JSON and AJAX are different when used in conjunction with jQuery?

Is it true that JSON serializes all data, preventing problems with client-side issues like cross-browser support? I've found using AJAX with jQuery to be straightforward, but I'm still unclear about the differences. I have also come across anot ...

Artistic Canvas: Selected Image

I am trying to determine if the user has clicked on an image drawn in a canvas element. Despite clicking on the image, nothing seems to be happening. The alert function is not being triggered and the last condition in the code never evaluates to true. An ...