简体   繁体   中英

How to Update Map when Map show based on longitude and latitude i.e; fetch from database

<form action="user-geolocation-confirm.php" method="post" name="myform" class="form-horizontal">
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <label for="latitude" class="control-label col-xs-4">Latitude</label>
                <input type="text" id="lat1" value="<?php echo $fetch['latitude'];?>"  name="latitude">
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <label for="longitude" class="control-label col-xs-4">Longitude</label>
                <input type="text" id="lang1" value="<?php echo $fetch['longitude'];?>"  name="longitude">
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <input type="submit" name="submit" class="btn btn-success"  value="Save">&nbsp;<?php
                    $url=  htmlspecialchars($_SERVER['HTTP_REFERER']);
                    echo "<a href='$url' class='btn btn-warning'> Back / Cancel</a>" ;?>
            </div>
        </div>
    </div>
</form>

<?php if(!empty($fetch['longitude']) && !empty($fetch['latitude'])){ ?>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
    var addssByGoogle='<?=$fetch['latitude']?>,<?=$fetch['longitude']?>';
    var geocoder;
    var map;
    var infowindow = new google.maps.InfoWindow();
    var marker;
    function initialize(address,xLocation,yLocation) 
    {
    codeLatLng(address,xLocation,yLocation) ;
    }

    function codeLatLng(address,xLocation,yLocation) 
    {
    var latlng = new google.maps.LatLng(xLocation,yLocation);
    var myOptions = {
    center: latlng,
    mapTypeId: 'roadmap'
    }
    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById("map_canvas1"), myOptions);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    if (results[0]) {
    if('1.366667'==xLocation && '103.8'==yLocation)
    {
    map.setZoom(9);
    }
    else
    {
    map.setZoom(12);
    }
    marker = new google.maps.Marker({
    position: latlng, 

    map: map,
    title: address
    }); 
    addssByGoogle = results[0].formatted_address;

    //infowindow.setContent(results[0].formatted_address);
    infowindow.setContent(address);
    infowindow.open(map, marker);
    } else {
    //        alert("No results found");
    }
    } else {
    //     alert("Geocoder failed due to: " + status);
    }
    });
    }

</script>

<div id="map_canvas1" style="width:100%; height:300px;"></div>
<script type="text/javascript">
    initialize("Latitude: <?=$fetch['latitude']?><br/> Longitude: <?=$fetch['longitude']?>","<?=$fetch['latitude']?>","<?=$fetch['longitude']?>");
</script>

<?php } else {?> 

<div id="googlemaps">The Postal Address Finder is powered by Google Maps. Loading..</div>


<!-- 
<script src="jquery.min.js.pagespeed.jm.TiC1blcYSb.js"></script>

<script src="bootstrap.min.js.pagespeed.jm.Rzv0qKF99s.js"></script>


<script>//<![CDATA[
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create','UA-50062-24','ctrlq.org');ga('send','pageview');
//]]></script>

-->

<script>//<![CDATA[
    (function(){var d=encodeURIComponent,f=window,g=document,h="documentElement",k="length",l="prototype",m="body",p="&",s="&ci=",t=",",u="?",v="Content-Type",w="Microsoft.XMLHTTP",x="Msxml2.XMLHTTP",y="POST",z="application/x-www-form-urlencoded",A="img",B="input",C="load",D="oh=",E="on",F="pagespeed_url_hash",G="url=";f.pagespeed=f.pagespeed||{};var H=f.pagespeed,I=function(a,b,c){this.c=a;this.e=b;this.d=c;this.b=this.f();this.a={}};I[l].f=function(){return{height:f.innerHeight||g[h].clientHeight||g[m].clientHeight,width:f.innerWidth||g[h].clientWidth||g[m].clientWidth}};I[l].g=function(a){a=a.getBoundingClientRect();return{top:a.top+(void 0!==f.pageYOffset?f.pageYOffset:(g[h]||g[m].parentNode||g[m]).scrollTop),left:a.left+(void 0!==f.pageXOffset?f.pageXOffset:(g[h]||g[m].parentNode||g[m]).scrollLeft)}};I[l].h=function(a){if(0>=a.offsetWidth&&0>=a.offsetHeight)return!1;a=this.g(a);var b=a.top.toString()+t+a.left.toString();if(this.a.hasOwnProperty(b))return!1;this.a[b]=!0;return a.top<=this.b.height&&a.left<=this.b.width};I[l].i=function(a){var b;if(f.XMLHttpRequest)b=new XMLHttpRequest;else if(f.ActiveXObject)try{b=new ActiveXObject(x)}catch(c){try{b=new ActiveXObject(w)}catch(e){}}if(!b)return!1;b.open(y,this.c+(-1==this.c.indexOf(u)?u:p)+G+d(this.e));b.setRequestHeader(v,z);b.send(a);return!0};I[l].k=function(){for(var a=[A,B],b=[],c={},e=0;e<a[k];++e)for(var q=g.getElementsByTagName(a[e]),n=0;n<q[k];++n){var r=q[n].getAttribute(F);r&&(q[n].getBoundingClientRect&&this.h(q[n]))&&!(r in c)&&(b.push(r),c[r]=!0)}if(0!=b[k]){a=D+this.d;a+=s+d(b[0]);for(e=1;e<b[k];++e){c=t+d(b[e]);if(131072<a[k]+c[k])break;a+=c}H.criticalImagesBeaconData=a;this.i(a)}};H.j=function(a,b,c){if(a.addEventListener)a.addEventListener(b,c,!1);else if(a.attachEvent)a.attachEvent(E+b,c);else{var e=a[E+b];a[E+b]=function(){c.call(this);e&&e.call(this)}}};H.l=function(a,b,c){var e=new I(a,b,c);H.j(f,C,function(){f.setTimeout(function(){e.k()},0)})};H.criticalImagesBeaconInit=H.l;})();pagespeed.criticalImagesBeaconInit('/mod_pagespeed_beacon','http://ctrlq.org/maps/address/','4CgYGHYGDX');
    //]]></script>

                         <?php }?>   
                            </div>

I would like to suggest to make two pages:

In first page you fetch longitude, latitude from database and use iframe to call map page. eg

<?php
/* Code to get latitude and longitude */
/* store value in $lat and $lon */ 
 $map_url = "map_php.php?lon=$lon&lat=$lat";
?>

<div id="maps" class="tab-pane fade">
 <div class="hpadding20">
   <iframe src="<?=$map_url?>" align="center" name="mymap" scrolling="No" width="100%" height="500" style="" frameborder="0"></iframe>
 </div>
</div>

In second page write code for map generating part. eg

<?php
$lat = $_GET["lat"];
 $lon = $_GET["lon"];
?>

 <!-- Placeholder for the Google Map -->
<div id="googleMap" style="width: 725px; height: 500px;"></div>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?    sensor=false"></script>
<script>
var myCenter=new google.maps.LatLng('<?=$lat?>', '<?=$lon?>');
function initialize()
{
  var mapProp = {
   zoom: 16,
   center:myCenter,
    mapTypeId:google.maps.MapTypeId.ROADMAP
 };

 var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

var marker=new google.maps.Marker({
   position:myCenter,
  });

marker.setMap(map);
}

 google.maps.event.addDomListener(window, 'load', initialize);
 </script>

Try it. I think it will work for you. Set map property and zoom level as per your requirement.

I have replicated a script using the link you have provided, it will ask for your location when you first open the page, and when you drag/drop marker than it will put the latitude and longitudes to the input box

<!DOCTYPE html>
<html lang="en">
    <head>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
        var map, latLng, marker, infoWindow, ad;
        var geocoder = new google.maps.Geocoder();

        function showAddress(val) {
            infoWindow.close();
            geocoder.geocode({
                'address': val
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    marker.setPosition(results[0].geometry.location);
                    geocode(results[0].geometry.location);
                } else {
                    alert("Sorry but Google Maps could not find this location.");
                }
            });
        }

        function geocode(position) {
            geocoder.geocode({
                latLng: position
            }, function(responses) {
                var html = '';
                window.location.hash = '#' + marker.getPosition().lat() + "," + marker.getPosition().lng();
                if (responses && responses.length > 0) {

                    html += '<p>Address: ' + responses[0].formatted_address + ' </p>';
                }
                html += 'Latitude : ' + marker.getPosition().lat() + '<br/>Longitude: ' + marker.getPosition().lng();
                document.getElementById('lat1').value = marker.getPosition().lat();
                document.getElementById('lang1').value = marker.getPosition().lng();
                map.panTo(marker.getPosition());
                infoWindow.setContent("<div id='iw'>" + html + "</div>");
                infoWindow.open(map, marker);
            });
        }

        function initialize() {
            var myOptions = {
                zoom: 12,
                panControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('googlemaps'), myOptions);
            var coordinates = window.location.hash;
            if (coordinates != "") {
                var hashlocation = coordinates.split(",");
                if (hashlocation.length == 2) {
                    showMap(hashlocation[0].substr(1), hashlocation[1], true);
                    return;
                }
            }
            if (navigator.geolocation) {
                defaultLocation();
                navigator.geolocation.getCurrentPosition(locationFound, defaultLocation);
            } else {
                defaultLocation();
            }
        }

        function locationFound(position) {
            showMap(position.coords.latitude, position.coords.longitude);
        }

        function defaultLocation() {
            showMap(38.8977, -77.0366);
        }

        function showMap(lat, lng, hideinfo) {
            latLng = new google.maps.LatLng(lat, lng);

            map.setCenter(latLng);
            marker = new google.maps.Marker({
                position: latLng,
                map: map,
                draggable: true,
                animation: google.maps.Animation.DROP
            });
            infoWindow = new google.maps.InfoWindow({
                content: '<div id="iw"><strong>Instructions:</strong><br /><br />Click and drag this red marker to spot exact location of your media.</div>'
            });
            if (hideinfo) {
                geocode(latLng);
            } else {
                infoWindow.open(map, marker);
            }
            google.maps.event.addListener(marker, 'dragstart', function(e) {
                infoWindow.close();
            });
            google.maps.event.addListener(marker, 'dragend', function(e) {
                var point = marker.getPosition();
                map.panTo(point);
                geocode(point);
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);

    </script>
    <style>
        #googlemaps
        {
            height: 400px;
            width: 700px;
        }
    </style>
</head>
<body>
    <label for="latitude" class="control-label col-xs-4">Latitude</label>
    <input id="lat1" value="" name="latitude" type="text">
    <label for="longitude" class="control-label col-xs-4">Longitude</label>
    <input id="lang1" value="" name="longitude" type="text">
    <div style="position: relative; background-color: rgb(229, 227, 223); overflow: hidden;" id="googlemaps"></div>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM