Solved

adding custom marker to google maps and calling google maps

Posted on 2015-02-02
14
199 Views
Last Modified: 2015-02-03
Hi
This has been covered all over the web but despite following instructions I can't get my custom marker to appear nor have an info box appear, onclick with a button to "get directions"
This is what I have:
var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    navigator.geolocation && navigator.geolocation.getCurrentPosition(showPosition, showError) == undefined && showError();

    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    var image;
    image = "blue_MarkerA.png";

    for (i = 0; i < locations.length; i++) {

        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
            icon: image

      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

Open in new window


where the icon is in the same folder as the html file hosting this code. So what have I done wrong?  I have also tried naming the icon directly in the function but that doesn't work either - I get no markers appearing... if I remove the icon code I get the default markers appearing.

The other part of the question is how do I then add a button to enable the user to get directions to that place via e.g. googlemaps app on their device?

thanks
0
Comment
Question by:lz7cjc
  • 7
  • 7
14 Comments
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40584384
It seems that just a file name is not enough, not sure why.. To make it look like a URL, I just changed it to:
image = "./blue_MarkerA.png"

Open in new window


For the directions, I got it to do something (hopefully close to what you want, in a link instead of a button for now), working off an example found here: https://developers.google.com/maps/documentation/javascript/examples/directions-simple?csw=1

Live example here: http://schutt.nl/ee/Q_28608218/

I attached the code instead of posting in a snippet because of the "i" in square brackets again... Please note some changes in the existing functions as well.
index.htm
0
 

Author Comment

by:lz7cjc
ID: 40584410
Thanks for this; however the new marker image is still not appearing. The directions is close but I was hoping to be able to tap into the directions/navigation functionality that comes with the google map. Is that possible?
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
ID: 40584548
Can you post your code or a link to your page? The image should be there, or try a full URL to your image?

For the directions: if you click the link I posted, on the left navigation there's a couple more examples. Should all be copy-paste but if you can't make it work, just tell me which one you need and I'll try building it in the page.
0
 

Author Comment

by:lz7cjc
ID: 40584673
i tried the full URL which I checked directly in the browser but still no joy
http://localhost/recharge/images/blue_MarkerA.png
the rest is what you kindly posted:
<script>


var locations = [['Everyone Active Hartham Leisure Centre', 51.800052, -0.077467],
        ['Gordons Gym', 51.480226, 0.069589],
        ['The Concorde Club', 51.48808, -0.40301],
        ['Croydon High Sports Club', 51.341246, -0.061708],
        ['Everyone Active Northolt Leisure Centre', 51.548934, -0.375026],
        ['Everyone Active Central Park Leisure Centre', 51.602689, 0.228719],
        ['Heston Community Sports Hall', 51.480955, -0.365949],
        ['Everyone Active Westminster Lodge Leisure Centre', 51.750365, -0.34032],
        ['Everyone Active Hornchurch Sports Centre', 51.563842, 0.207556],
//...
        ['The Landmark Spa and Health Club', 51.521554, -0.161116],
        ['Brands Hatch Place Hotel and Spa', 51.361902, 0.269406],
        ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var center;
    navigator.geolocation && navigator.geolocation.getCurrentPosition(showPosition, showError) == undefined && showError();

    var infowindow = new google.maps.InfoWindow();

    var marker, i, image = "http://localhost/recharge/images/blue_MarkerA.png";
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
        icon: image
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0] + '<br/><a href="javascript:calcRoute('+i+')">How do I get there?</a>');
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

function calcRoute(i) {
  infowindow.close(); // optional
  var request = {
      origin: center, // only useful when we did get a current location...
      destination: new google.maps.LatLng(locations[i][1], locations[i][2]),
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

function showPosition(position) {
  lat = position.coords.latitude;
  lon = position.coords.longitude;
  latlon = new google.maps.LatLng(lat, lon);
  map.setCenter(center = latlon);
}

function showError(error) {
  map.setCenter(center = new google.maps.LatLng(locations[0][1], locations[0][2])); // default 1st from array
}

</script>

Open in new window

0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40584690
Hmm, localhost should work for you unless the image needs to be accessible from Google's servers for some reason (well specifically the reason would be the way the icon is created but I wasn't aware that would be an issue). Is there any publicly available website where you can host the image? If not can you try pointing it to my image (http://schutt.nl/ee/Q_28608218/blue_MarkerA.png) so we know at least that's what's going on?
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40584692
PS: have you tried pressing F12 in the browser and inspecting the console and network tabs to see if there's an error regarding the image?
0
 

Author Comment

by:lz7cjc
ID: 40584718
i tried your server but it made no difference
I looked through the sources and it was odd that was nothing there about the image see attached
there was nothing in console and network
sources.png
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40584736
Please try refreshing the page with the F12/dev tools already open. Also, it normally shouldn't make a difference but clearing the cache beforehand can sometimes help.
0
 

Author Comment

by:lz7cjc
ID: 40584787
cleared cache
this is the html source:
  var center;
    navigator.geolocation && navigator.geolocation.getCurrentPosition(showPosition, showError) == undefined && showError();

    var infowindow = new google.maps.InfoWindow();

    var marker, i, image = "http://schutt.nl/ee/Q_28608218/blue_MarkerA.png";
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
        icon: image
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0] + '<br/><a href="javascript:calcRoute('+i+')">How do I get there?</a>');
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

Open in new window

Attached is the network readout which shows a call being made to your server but not sure if there is anything unusual there? (6th one down)
network.png
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40584973
That looks ok to me. So how does the map look for you? any big difference between my version and your 'localhost' version? do you see the map all right, see the standard "red drop" marker images scattered around London?

I attached a capture of what I see just to make sure we're talking about the same thing.

One piece of code I saw on the google dev pages, but shouldn't make a difference... in the marker setting you could try:
icon: new google.maps.MarkerImage(image)

Open in new window


capture
0
 

Author Comment

by:lz7cjc
ID: 40585800
unfortunately I just get an empty map, centred to my current position. I tried adding in that line of code and now the call isn't being made to your server.
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40585904
"Empty map" but showing cities, roads etc right, or is that even missing?

Is your location in or around London? Otherwise try going there (grasping at straws here...), try zooming out to see if the markers are elsewhere on the world by mistake, try disabling "current location" (so it will go to the first location in the array).

Keep making sure with F12 that any editing doesn't cause a javascript/network error.

Are you still testing on localhost? Any chance you could put it on a public webserver to test (if only for yourself)?
0
 

Author Comment

by:lz7cjc
ID: 40585941
success! I switched from the fixed list to the dynamic list via the DB and now it works. I now want to change the marker based on price so am going to post another question for that... think you have more than earnt this one!
0
 

Author Comment

by:lz7cjc
ID: 40585952
have put the new question here if you would like to carry on helping me! thanks for all you have done so far
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28608952.html
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The purpose of this video is to demonstrate how to Import and export files in WordPress. This will be demonstrated using a Windows 8 PC. Go to your WordPress login page. This will look like the following: mywebsite.com/wp-login.php : Click on Too…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now