Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add local image as custom marker in google maps

i'm trying to create a custom marker using google maps.

var iconBase = //some url;
var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: iconBase + 'marker.png'
});

This basically works. I host my images in a google drive. It's good, but a little slow, takes about 500-700ms to load the image for the first time upon clicking to a map and rendering the marker. So I'm trying to add the image locally, sadly, I can't seem to find resources regarding this one. How do I use local (in my project directory) images?

Assuming I put it in a folder "icons" within the same directory level as my php file where I call google maps services, if that helps. Thank you!

Update!

I tried:

maker = new google.maps.Marker({
              position: location,
              map: globalMap,
              icon : "pubIcons/male-2.png"
            }); 

where pubIcons is a folder in the same directory as the php file where I render the map. and I get this error :

GET http://localhost/bims-2.0/index.php/location/view/pubIcons/male-2.png 404 (Not Found) 

It sort of behaves like pubIcons/male-2.png is an action in my controller "view", i'm using Yii btw.

like image 407
muffin Avatar asked Jan 10 '23 23:01

muffin


2 Answers

Try this code :)

var image = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQxFoh469eOsZQkuPOLpZn3R6yyIExkZCxOxf4ywfeY3v330EwP3Q";
var marker = new google.maps.Marker({
        position: location,
        map: globalMap,
        icon: image
});

Update

var image  = "http://yourdomain.com/image/image.php";

or

icon : "/pubIcons/male-2.png"
like image 199
HoangHieu Avatar answered Feb 04 '23 20:02

HoangHieu


I also came across this issue but resolved it a different way. I use Django for my web framework and Django makes use of a directory called static. Don't know if this dir can be used outside of Django. I loaded the pic into my static file and in my webpage's body tag, had the code

<div style="display:none">

    `<img src="{% static 'map/CrocMarker_45.png' %}" alt="Croc Marker" id="crocMark">`

</div>

In this case, I set the display to none because I don't want to render the pic in the body tag, just want to load it so that I can access it in my maps scripts.

In my function initMap() I create the variable var crocMark=document.getElementById("crocMark").src;.

Later, when you're creating your markers, you can just set the icon to this variable. For example:

var XMarker=new google.maps.Marker({ position: location, map: map_name, icon: crocMark });

This may not be the best way, but it worked great for me and I hope it does for you as well.

Edit: Just a note, here's my project structure if it wasn't clear.

Project Root "Django">Django Root "Django_Project">My apps e.g. "map">static>map
like image 36
Jimmy Avatar answered Feb 04 '23 20:02

Jimmy