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

Illustrating a fresh DOM element with intro.js

I am currently utilizing intro.js to create a virtual 'tour' for my website. As I aim to provide a highly interactive experience for users, I have enabled the ability for them to engage with highlighted DOM elements at different points in the tou ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

Utilizing PHP, Javascript, and jQuery in mobile technology gadgets

Can anyone recommend mobile technology products that have been developed using PHP, Javascript, and jQuery? What are the newest mobile products available on the market that have been built using these languages? Do popular devices like iPhone, BlackBerry ...

Uh oh! An error occurred while trying to create the ngFileUpload module

After using NuGet to install Angular File Upload 12.2.13, I made sure to inject the dependencies correctly. However, despite this, I keep encountering the following error: angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module c ...

What steps can be taken to diagnose the cause of a failed Jquery AJAX request?

I am attempting to utilize the Yahoo Finance API to retrieve data in CSV format through Javascript. However, my current implementation shown below is not successful. $.ajax({ type: "GET", url: "http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3j ...

What steps should I take to ensure that the array yields the correct output?

Why is my code not creating an array of [0, 1, 2] when I pass the number 3 as a parameter? const array = [0]; const increment = (num) => { if (num > 0) { increment(num - 1); array.push(num); } return; }; console.log(array); incremen ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Adjust the alignment and floating of text within an iframe on the same domain

Is it possible to align text on the right side of an iframe that contains a width and text inside? The iframe's src is from the same domain. If so, how can this be achieved through JavaScript? ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Click on the checkbox to activate it using JavaScript

I'm trying to use JavaScript to toggle the checkbox status when clicking a button. The first button is supposed to uncheck the box and it's working correctly: function clear() { document.getElementById("check").checked = ""; } However, I al ...

Dynamic styling based on conditions in Next.js

After a lengthy hiatus, I'm diving back in and feeling somewhat disconnected. In short, I have encountered a minor challenge. I successfully created a navigation menu pop-out that toggles classname based on the isActive condition in React. However, I& ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

Navigating to the most recent item within ng-repeat (AngularJS or JavaScript)

I am working on a feature where posts are displayed using ng-repeat in a div, and users can enter new posts in an input box. The posts are sorted so that the latest one appears at the bottom. After adding a new post, I want to automatically scroll down t ...

Methods for removing and iterating through images?

I successfully programmed the image to move from right to left, but now I want to add a function where the image is deleted once it reaches x: 50 and redrawn on the left. I attempted to use control statements like "if," but unfortunately it did not work a ...

Accessing an object within an array in a Node.js EJS file

Great job everyone! I've developed a project using Node.js which includes the following schema structure: const debt = new Schema({ name: { type: String, required: true, }, medicine: [{ data: { type: Schema.Types.ObjectId, ...

ng-include once the application has finished loading

Currently, my server is using handlebars to generate the initial HTML page. I would like to include a ng-include in this page to dynamically update the client side. However, every time my application runs, it loads the page and the data-ng-include="templa ...

The Node.js express-generator application encounters a problem and is unable to start because of a TypeError: app.set function is not recognized

During the setup of my application using nodejs and express-generator, I encountered an issue when running the following commands in my terminal: npm install multer --save npm audit fix Afterwards, when I attempted to run node ./bin/www I received an err ...

The quickest regular expression match possible if it is already a subsection of another match

Is there a simple way to find the shortest match in a long text where strings are repeated? I'm having trouble because matches within already matched text aren't being found. Here's an example of the issue: Using code: "ababc".match(/a.+c ...

When trying to log the parsed JSON, it unexpectedly returns undefined even though it appears to be in good

Everything was working fine until a couple of days ago. Let's consider this as my PHP script: echo json_encode(array('stat'=>'ok')); I am sending an AJAX request to this script: $.post(base_url+'line/finalize/', {t ...

Modify capital letters to dashed format in the ToJSON method in Nest JS

I am working with a method that looks like this: @Entity() export class Picklist extends BaseD2CEntity { @ApiHideProperty() @PrimaryGeneratedColumn() id: number; @Column({ name: 'picklist_name' }) @IsString() @ApiProperty({ type: Str ...