Display Custom Marker in Google Maps Using Relativ

2019-07-20 08:30发布

问题:

This question already has an answer here:

  • Using a Relative Path in Javascript to Set Google Map Icon 1 answer

I am using Google's Javascript APi v.3.0 to develop a web app. I want to be able to display custom markers, but they don't show up when I try to add them. I've written a helper function in Javascript to display a custom marker:

function addCustomMarker(iconFile,iconTitle,lat,lng){
   var loc = new google.maps.LatLng(lat,lng);
   var marker = new google.maps.Marker({
      position:loc,
      icon:iconFile,
      title: iconTitle,
      zIndex:2
   });
   marker.setMap(map);//Where map is a google.maps.Map already defined
}

I'm currently testing locally and my file structure sort of looks like:

  • /Maps Application
    • map.htm
    • /Images
      • markerImage.png

Elsewhere in the html file, I then call the javascript function like:

addCustomMarker('Images/markerImage.png', 'Custom Marker', 20, 50);

However, this does not work. No marker is displayed. If I comment out the "icon: markerIcon," line, then the default marker is displayed, which tells me that it can't find the image file.

Is there a way to reference marker images from a relative path like I am trying to do? I've tried './Images/markerImage.png' and '/Images/markerImage.png' as well, and neither work.

回答1:

Yes, I also think relative paths work. I tried it locally and it works fine. I believe icon: just places the value into a src of an img tag, or something of the sort.

Here's my example:

var marker = new google.maps.Marker({map: map, 
  position: new google.maps.LatLng(0,0), 
  icon: "icons/ride_red.png"});

icons is a folder in the same folder where the JavaScript/HTML file is.

Are you sure you have the capitalization correct? What if you tried "hardcoding" the icon option, that is:

icon: 'Images/markerImage.png',

Now here's a silly question: have you also tried opening that markerImage.png in your browser?

Beside local pages, here's a page that has relative icon paths. You check the "Metro SP Stations" checkbox to display the icons. If you look at the source,

     estacao = new google.maps.Marker({
        map: map,
        position: toLatLng(estacao_data.posn[0], estacao_data.posn[1]),
        icon: 'metrosp/' + estacao_data.icon[0] + '.png',
        title: estacao_data.name,
        visible: false
      });

Then you can navigate to the metrosp folder and see the images are all there:

https://files.nyu.edu/hc742/public/googlemaps/metrosp/



回答2:

No, you can't use a relative address for the image. The pin is displayed on a page from a different server, so you have to use the complete address.