Issues Questions Integrate search location and save marker in database

asked on

Hello, Thank You for this code. Its really great and helpful. I tried to implement this with google maps places. But it neither show error nor work. Could you help me please. process_map.php file is same. I have changed the map_initialized function only. Below is my code. Thank You

<!DOCTYPE html>
<html>
<head>
<title>Google Map</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBLYjqck5Db1nsyV2mEs7YjJpHC15Hkb_Y&libraries=places"></script>
<script type="text/javascript">
$(document).ready(function() {

    var mapCenter = new google.maps.LatLng(27.7172, 85.3240); //Google map Coordinates
    var map;
    google.maps.event.addDomListener(window, 'load', map_initialize);
    // map_initialize(); // initialize google map

    //############### Google Map Initialize ##############
    function map_initialize()
    {
        var map = new google.maps.Map(document.getElementById('google_map'), {
            center: mapCenter,
            zoom: 13,
            mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
            searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
            var places = searchBox.getPlaces();

            if (places.length == 0) {
                return;
            }

            // Clear out the old markers.
            markers.forEach(function(marker) {
                marker.setMap(null);
            });
            markers = [];

            // For each place, get the icon, name and location.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function(place) {
                if (!place.geometry) {
                    console.log("Returned place contains no geometry");
                    return;
                }
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };

                // Create a marker for each place.
                markers.push(new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                }));

                if (place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
            });
            map.fitBounds(bounds);
        });         

        //Load Markers from the XML File, Check (map_process.php)
        $.get("map_process.php", function (data) {

            $(data).find("marker").each(function () {
                  var name      = $(this).attr('name');
                  var address   = '<p>'+ $(this).attr('address') +'</p>';
                  var type      = $(this).attr('type');
                  var point     = new google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));

                  create_marker(point, name, address, false, false, false, "http://travelomaker.com/img/icons/pin_blue.png");
            });
        }); 

        //Right Click to Drop a New Marker
        google.maps.event.addListener(map, 'rightclick', function(event) {
            //Edit form to be displayed with new marker
            var EditForm = '<p><div class="marker-edit">'+
            '<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">'+
            '<label for="pName"><span>Place Name :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>'+
            '<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>'+
            '<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option value="restaurant">Rastaurant</option><option value="bar">Bar</option>'+
            '<option value="house">House</option></select></label>'+
            '</form>'+
            '</div></p><button name="save-marker" class="save-marker">Save Marker Details</button>';

            //Drop a new Marker with our Edit Form
            create_marker(event.latLng, 'New Marker', EditForm, true, true, true, "http://----PATH-TO-YOUR-WEBSITE-ICON-------/icons/pin_green.png");
        });

    }

    //############### Create Marker Function ##############
    function create_marker(MapPos, MapTitle, MapDesc,  InfoOpenDefault, DragAble, Removable, iconPath)
    {                 

        //new marker
        var marker = new google.maps.Marker({
            position: MapPos,
            map: map,
            draggable:DragAble,
            animation: google.maps.Animation.DROP,
            title:"Hello World!",
            icon: iconPath
        });

        //Content structure of info Window for the Markers
        var contentString = $('<div class="marker-info-win">'+
        '<div class="marker-inner-win"><span class="info-content">'+
        '<h1 class="marker-heading">'+MapTitle+'</h1>'+
        MapDesc+ 
        '</span><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>'+
        '</div></div>');    

        //Create an infoWindow
        var infowindow = new google.maps.InfoWindow();
        //set the content of infoWindow
        infowindow.setContent(contentString[0]);

        //Find remove button in infoWindow
        var removeBtn   = contentString.find('button.remove-marker')[0];
        var saveBtn     = contentString.find('button.save-marker')[0];

        //add click listner to remove marker button
        google.maps.event.addDomListener(removeBtn, "click", function(event) {
            remove_marker(marker);
        });

        if(typeof saveBtn !== 'undefined') //continue only when save button is present
        {
            //add click listner to save marker button
            google.maps.event.addDomListener(saveBtn, "click", function(event) {
                var mReplace = contentString.find('span.info-content'); //html to be replaced after success
                var mName = contentString.find('input.save-name')[0].value; //name input field value
                var mDesc  = contentString.find('textarea.save-desc')[0].value; //description input field value
                var mType = contentString.find('select.save-type')[0].value; //type of marker

                if(mName =='' || mDesc =='')
                {
                    alert("Please enter Name and Description!");
                }else{
                    save_marker(marker, mName, mDesc, mType, mReplace); //call save marker function
                }
            });
        }

        //add click listner to save marker button        
        google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker); // click on marker opens info window 
        });

        if(InfoOpenDefault) //whether info window should be open by default
        {
          infowindow.open(map,marker);
        }
    }

    //############### Remove Marker Function ##############
    function remove_marker(Marker)
    {

        /* determine whether marker is draggable 
        new markers are draggable and saved markers are fixed */
        if(Marker.getDraggable()) 
        {
            Marker.setMap(null); //just remove new marker
        }
        else
        {
            //Remove saved marker from DB and map using jQuery Ajax
            var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
            var myData = {del : 'true', latlang : mLatLang}; //post variables
            $.ajax({
              type: "POST",
              url: "map_process.php",
              data: myData,
              success:function(data){
                    Marker.setMap(null); 
                    alert(data);
                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert(thrownError); //throw any errors
                }
            });
        }

    }

    //############### Save Marker Function ##############
    function save_marker(Marker, mName, mAddress, mType, replaceWin)
    {
        //Save new marker using jQuery Ajax
        var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
        var myData = {name : mName, address : mAddress, latlang : mLatLang, type : mType }; //post variables
        console.log(replaceWin);        
        $.ajax({
          type: "POST",
          url: "map_process.php",
          data: myData,
          success:function(data){
                replaceWin.html(data); //replace info window with new html
                Marker.setDraggable(false); //set marker to fixed
                Marker.setIcon('http://----PATH-TO-YOUR-WEBSITE-ICON-------/icons/pin_blue.png'); //replace icon
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError); //throw any errors
            }
        });
    }

});
</script>

<style type="text/css">
h1.heading{padding:0px;margin: 0px 0px 10px 0px;text-align:center;font: 18px Georgia, "Times New Roman", Times, serif;}

/* width and height of google map */
#google_map {width: 90%; height: 500px;margin-top:0px;margin-left:auto;margin-right:auto;}

/* Marker Edit form */
.marker-edit label{display:block;margin-bottom: 5px;}
.marker-edit label span {width: 100px;float: left;}
.marker-edit label input, .marker-edit label select{height: 24px;}
.marker-edit label textarea{height: 60px;}
.marker-edit label input, .marker-edit label select, .marker-edit label textarea {width: 60%;margin:0px;padding-left: 5px;border: 1px solid #DDD;border-radius: 3px;}

/* Marker Info Window */
h1.marker-heading{color: #585858;margin: 0px;padding: 0px;font: 18px "Trebuchet MS", Arial;border-bottom: 1px dotted #D8D8D8;}
div.marker-info-win {max-width: 300px;margin-right: -20px;}
div.marker-info-win p{padding: 0px;margin: 10px 0px 10px 0;}
div.marker-inner-win{padding: 5px;}
button.save-marker, button.remove-marker{border: none;background: rgba(0, 0, 0, 0);color: #00F;padding: 0px;text-decoration: underline;margin-right: 10px;cursor: pointer;
}
</style>
</head>
<body>             
<div align="center">Right Click to Drop a New Marker</div>
<input id="pac-input" class="controls" type="text" placeholder="Search Box" style="width: 300px;">
<div id="google_map"></div>
</body>
</html>
  • 1Un-comment map_initialize();
Add Answer
All HTML codes will be stripped in the comment, except inline <code> HTML tag.
1 Answer
answered on

I have initialized the map with <code>google.maps.event.addDomListener(window, 'load', map_initialize);</code> .

    All HTML codes will be stripped in the comment, except inline <code> HTML tag.

    Can You Answer this? Help us answer the question!

      • Answer
      Supports basic Markdown syntax. Excluded syntaxes (Headers, Lists, Blockquotes, Table, Images)