Theodoros80
Theodoros80

Reputation: 796

Adding the first marker on map and geocoding

The application,then the problem i am facing.

Application: Read JSON and add markers to the map according the JSON query.<-Works OK.

Then when user clicks on map, add a marker and show infowindow with the current address.

The second step works, only when the user clicks on the map for the second time(and from that point works every time). When the user click on the map for the first time, the marker is added to the position but the reverse geocoding doesn't work i.e the infowindow doesn't show.

From my debug so far, if you see at function dam(latLng) , console.log("dam 1"); if called at the first click. console.log("dam 2"); if called only after the second click on the map, so my guess is that the problem is somewhere there.

Any help?

My code:

<script type="text/javascript">
        $(function () {
            var map;
            var arrMarkers = [];
            var arrInfoWindows = [];
            var marker = null;
            var infowindow = new google.maps.InfoWindow({
                //size: new google.maps.Size(150,50)
            });

            var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(40.650906,22.88229),
      new google.maps.LatLng(40.601918,23.011723));

            var input = document.getElementById('searchTextField');
            var autocomplete = new google.maps.places.Autocomplete(input, {
                types: ["geocode"], bounds: defaultBounds
            });

            google.maps.event.addListener(autocomplete, 'place_changed', function (event) {
                infowindow.close();
                var place = autocomplete.getPlace();
                if (place.geometry.viewport) {
                    map.fitBounds(place.geometry.viewport);
                } else {
                    map.setCenter(place.geometry.location);
                    map.setZoom(17);
                }

                //moveMarker(place.name, place.geometry.location);
                map.setCenter(place.geometry.location);
                $('.MapLat').val(place.geometry.location.lat());
                $('.MapLon').val(place.geometry.location.lng());
            });

            function moveMarker(placeName, latlng) {
                //marker.setIcon(image);
                marker.setPosition(latlng);
                infowindow.setContent(placeName);
                infowindow.open(map, marker);
            }

            function createMarker(latlng, name, html) {
                var contentString = html;

                var marker = new google.maps.Marker({
                    position: latlng,
                    map: map,
                    zIndex: Math.round(latlng.lat() * -100000) << 5,
                    draggable: false
                });
                google.maps.event.addListener(marker, 'rightclick', function (event) {
                    marker.setMap(null);
                });

                google.maps.event.addListener(marker, 'click', function () {
                    //infowindow.setContent(contentString); 
                    //infowindow.open(map,marker);
                });

                google.maps.event.trigger(marker, 'click');
                return marker;
            }


            function mapInit() {

                var styles = [{
                    featureType: "poi.business",
                    stylers: [{
                        visibility: "off"
                    }]
                }]

                var styledMap = new google.maps.StyledMapType(styles, {
                    name: "Styled Map"
                });

                var centerCoord = new google.maps.LatLng(40.629956, 22.95413);
                var mapOptions = {
                    zoom: 14,
                    center: centerCoord,
                    disableDoubleClickZoom: true,
                    mapTypeControl: true,
                    mapTypeControlOptions: {
                        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                        position: google.maps.ControlPosition.BOTTOM_CENTER
                    },
                    panControl: false,
                    zoomControl: false,
                    streetViewControl: false,


                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map(document.getElementById("map"), mapOptions);
                map.mapTypes.set('map', styledMap);
                map.setMapTypeId('map');

                $.getJSON("http://PATH_TO_JSON", {}, function (data) {
                    $.each(data.places, function (i, item) {
                        $("#markers").append('<li><a href="#" rel="' + i + '">' + item.title + '</a></li>');
                        var marker = new google.maps.Marker({
                            position: new google.maps.LatLng(item.lat, item.lng),
                            map: map,
                            title: item.title,
                            //animation:google.maps.Animation.DROP,

                        });
                        arrMarkers[i] = marker;
                        var infowindow = new google.maps.InfoWindow({
                            content: "<h3>" + item.title + "</h3>" + item.description + "<br><img class='img-rounded' src='alertimages/" + item.image + "'/>"
                        });
                        arrInfoWindows[i] = infowindow;
                        google.maps.event.addListener(marker, 'click', function () {
                                 map.setCenter(marker.getPosition());
                    //toggleBounce();
                            for (x = 0; x < arrInfoWindows.length; x++) {
                                arrInfoWindows[x].close();
                            }
                            infowindow.open(map, marker);
                        });
                        function toggleBounce() {

              if (marker.getAnimation() != null) {
                marker.setAnimation(null);
              } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
              }
            }
                    });
                });


                function dam(latLng) {
                console.log("dam 1");
                    google.maps.event.addListener(map, 'click', function (event) {
        console.log("dam 2");

                        $('.MapLat').val(event.latLng.lat());
                        $('.MapLon').val(event.latLng.lng());
                        //infowindow.close();
                        var geocoder = new google.maps.Geocoder();
                        geocoder.geocode({
                            "latLng": event.latLng
                        }, function (results, status) {
                            console.log(results, status);
                            if (status == google.maps.GeocoderStatus.OK) {
                                console.log(results);
                                var lat = results[0].geometry.location.lat(),
                                    lng = results[0].geometry.location.lng(),
                                    addr_name = results[0].address_components[1].long_name,
                                    addr_num = results[0].address_components[0].long_name
                                    latlng = new google.maps.LatLng(lat, lng);


                                $("#searchTextField").val(results[0].formatted_address);
                                infowindow.setContent(addr_name + " " + addr_num + "<br><a href='marker.php?lat="+lat+"&lng="+lng+"&adr="+results[0].formatted_address+"'/>add marker</a>");
                                infowindow.open(map, marker);

                            } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                                setTimeout(function () {
                                    dam(latLng);
                                }, 200);
                            }
                        });
                    });

                }

               // google.maps.event.addListener(map, 'click', function () {
                    //infowindow.close();
               // });

                google.maps.event.addListener(map, 'click', function (event) {
                infowindow.close();
                    if (marker) {
                        marker.setMap(null);
                        marker = null;

                    }
                    //marker = createMarker(event.latLng, "name", "<b>Location</b><br>"+event.latLng,dam(event.latLng));
                    marker = createMarker(event.latLng, dam(event.latLng));
                });

            }

            $(function () {
                // initialize map (create markers, infowindows and list)
                mapInit();

                $("#markers").on("click", "a", function () {
                    var i = $(this).attr("rel");
                    // this next line closes all open infowindows before opening the selected one
                    for (x = 0; x < arrInfoWindows.length; x++) {
                        arrInfoWindows[x].close();
                    }
                    arrInfoWindows[i].open(map, arrMarkers[i]);
                });
            });
        });
    </script>

Upvotes: 0

Views: 427

Answers (1)

Theodoros80
Theodoros80

Reputation: 796

Never mind i found it. I had to remove

google.maps.event.addListener(map, 'click', function (event) { from dam function and change

"latLng": event.latLng to "latLng": latLng. Thanks for reading!

Upvotes: 1

Related Questions