Search code examples
javascriptgoogle-mapsgoogle-maps-api-3directions

Google Map with Routeplanner don't shows marker and info window correctly


I have searched the whole day, but didn't find a solution. I would be glad if someone see my mistake. I try to show a map with marker, which opens the infowindow on click. This I did many times before. Inside the infowindow I want to show the option to change to Google for routeplanning.

The function for locating and linking to Google works great, but onload the map appears without showing the marker, but showing the infowindow directly and open.

You can see the map here: https://jsfiddle.net/fuy8n47d/

This is my code so far:

<div class="mapwrapper">
<div id="map_canvas"></div>

<!-- STARTING MAP DEFINITION -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&language=de"></script>
<script type="text/javascript">

    var map;
    var start = new google.maps.LatLng(50.6472671, 8.4210159);
    var geocoder;
    geocoder = new google.maps.Geocoder();

    // Initalize your map
    function initialize() {
        var mapOptions = {
            zoom:16,
            scrollwheel: false,
            panControl: true,
            draggable: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: start
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    }

    // Collect entered data and open Google Maps in a new browser tab
    function showRoute() {
        var start = document.getElementById("address").value;
        var dest_url = "http://maps.google.de/maps?saddr="+start+"&daddr="+destination;
        window.open(dest_url, '_blank');
    }

    // Define infobox widget
    function codeAddress() {
        var marker = new google.maps.Marker({
            map: map,
            position: new google.maps.LatLng(50.6472671, 8.4210159 ),
            title:"Info Window title goes here"
        });

        var address = destination;
        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var coordInfoWindow = new google.maps.InfoWindow({
                    content: "<h2>Your Way to Us</h2><p>Enter your location<br>and press 'FIND'</p><input id='address' type='textbox' value='' style='border: 1px solid #f0f0f0;-webkit-border-radius: 8px;-moz-border-radius: 8px;border-radius: 8px;'> <input type='button' value='FIND' onClick='showRoute();'>",
                    map: map,
                    position: results[0].geometry.location
                });
            } else {
                alert("Geocode not available: " + status);
            }
        });
        google.maps.event.addListener(marker, 'click', function() {
            coordInfoWindow.open(map,marker);
        });
    }

    // Automatic geo localisation
    function codeLatLng() {
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = new google.maps.LatLng(position.coords.latitude,
                        position.coords.longitude);

                geocoder.geocode({'latLng': pos}, function(results, status) {

                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[1]) {
                            document.getElementById("address").value = results[1].formatted_address;
                        } else {
                            // alert("No results found");
                        }
                    } else {
                        // alert("Geocoder failed due to: " + status);
                    }
                });

            }, function() {
                //
            });
        }
    }

    // DO NOT CHANGE CODE ABOVE!

    // Change custom parameters starting from here:
    var destination = "Mainzer Dom, Markt, Mainz"; // destination, your address
    document.getElementById('map_canvas').style.width = '100%'; // map width
    document.getElementById('map_canvas').style.height = '700px'; // map height
    initialize();
    codeAddress();
    codeLatLng();


</script>
<!-- END OF MAP DEFINITION -->

</div>

What do I wrong, does anybody know? I would be thankful for your help, thanks a lot,

Thomas


Solution

  • Ok, so as I get no help on this post, I helped myself ;-) As far as I'm not a GoopleMaps API expert, I found a solution, which works for my project. I'm missing the automatically geolocation now, but marker and infowindow behave now as I expect it. I post this code and hope, it helps somebody with a simular problem. Here it is:

    function initialize() {
      var mapOptions = {
        center: new google.maps.LatLng(49.9988999, 8.2717569 ),
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false,
        panControl: true,
        draggable: false
      };
      var map = new google.maps.Map(document.getElementById("map_canvas"),
                                    mapOptions);
      var marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(49.9988999, 8.2717569 ),
        title:"Info Window title goes here"
      });
      // Adjust styling of info window depending on the map height and webpage design
      var contentString = '<div id="mapinfo_box" style="color:#666;max-width:280px;">'+
          '<h1 id="mapinfo_h1">Info Window title goes here, too</h1>'+
          '<div id="mapinfo_body">'+
          '<p style="font-size:16px;margin-bottom:15px;">Examplestreet 6 <br />12345 ExampleCity</p>'+
          '<form action="http://maps.google.com/maps" method="get" target="_blank"><label for="saddr">Enter your location</label><br />'+
          '<input id="saddr" type="text" name="saddr" /><input type="hidden" name="daddr" value="Staatstheater Mainz - Großes Haus" />'+
          '<input type="submit" value="Get Route" /></form>'+
          '</div>';
      var infowindow = new google.maps.InfoWindow({
        content: contentString
      });
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
      });
    }
    google.maps.event.addDomListener(window, 'resize', initialize);
    google.maps.event.addDomListener(window, 'load', initialize)
    html { 
      height: 100%; 
    }
    body {
      height: 100%;
      margin: 0; 
      padding: 0; 
    }
    #sec4 {
      width: 100%;
      height: 50%;
    }
    #map_canvas { 
      width: 100%; height: 600px; 
    }
    <!-- Insert Googlemap Api -->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&language=de"></script>
    
    <div id="sec4" onload="initialize()">
     <div id="map_canvas"></div>
    </div>

    Ok, I'm surely not a map API expert, but the code works for me and the map is responsive. If somebody sees a mistake, feel free to correct me.