简体   繁体   中英

google maps - reverse geocoding

I don't know much javascript and I'm not too familiar with google maps so I'm struggling a little here but I have a map implemented with a circle drawn round it. I also have a slider which allows you to increase the circle radius.

When someone moves the marker, my circle moves along with it ok, and the appropriate hidden input in my form updates so that I can get the latLng and save to daabase.

But I also want to get a human readable address when the user has moved the marker, so I reverse geocode. This is where I'm having problems, it's reverse geocoding ok, but now I can no longer move the marker. I know it's probably something simple but I don't even know how I've got as far as I have let alone whats wrong. Can anyone help me out?

My map is at http://www.liquidlizard.net/users/trainer

and here's a dump of the code I'm using:

http://pastebin.com/T6Sa92Af

EDIT - and the code as requested

<?php
echo $this->Html->script('https://maps.googleapis.com/maps/api/js?sensor=false', array('inline' => false));
?> 

<div class="alignCenter bottomBorder marginBot36">
    <div class="widthContainer padBot18 padTopt18">
        <?php echo $this->Html->image('icon-round-marker-pink.png', array('class'=>'midAlignImg'));?>
    </div>  
    <div class="widthContainer fontTwentySeven padBot18">
        Which locations do you cover?
    </div>
    <div class="singleColForm alignLeft fontFourteen" style="border:none">
        <div class="left"><?php echo $this->Html->image('mileradius.png');?></div>
        <div class="right" id="sliderHolder">
            <div id="slider"></div>
        </div>
        <div style="clear:both;height:18px"></div>
        <div id="map-canvas"></div>
        <div id="map-numOf-miles" class="alignCenter fontPurple fontNineteen">0 Miles</div>
    </div>
    <div class="addButton strong">ADD</div>
</div>
<?php // hidden inputs for locations
echo $this->Form->hidden('miles', array('id'=>'miles'));
echo $this->Form->hidden('location', array('id'=>'location'));
?>




<script type="text/javascript">
$(document).ready(function() {  


    //User clicks to add location
    $(".addButton").click(function() {
        $.post( "<?php echo $this->webroot;?>locations/add", { name: "John", time: "2pm" })
                .done(function( data ) {
                alert( "Data Loaded: " + data );
           });
    });

    //Google Maps
        var userLocation = "London";
        var geocoder = new google.maps.Geocoder();
        var circle;
        var latLng;
        var marker;

        $( "#slider" ).slider({
            slide: function(event, ui) {
                $("#map-numOf-miles").html(ui.value+' Miles');
                $("#miles").val(ui.value);
                circle.setRadius(ui.value/0.0621371192*100);
            }
        });

            //Google Maps
            function initialize() {
                var styles = [
                  {
                        stylers: [
                          { hue: "#00ffe6" },
                          { saturation: -20 }
                        ]
                  }
                ];

                geocoder.geocode( {"address": userLocation}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                            latLng = results[0].geometry.location;
                            //alert (latLng);
                            var mapOptions = {
                              center: latLng,
                              zoom: 6,
                              styles: styles,
                              mapTypeId: google.maps.MapTypeId.ROADMAP
                            };

                            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

                            marker = new google.maps.Marker({
                                map: map,
                                position: latLng,
                                draggable: true
                            });

                            circle = new google.maps.Circle({
                                map: map,
                                radius: 0, //your radius in meters
                                strokeColor: '#d12d87',
                                strokeOpacity: 0.35,
                                strokeWeight: 2,
                                fillColor: '#d12d87',
                                fillOpacity: 0.35,
                                center: latLng
                            });


                        $("#location").val(results[0].geometry.location);
                        google.maps.event.addListener(marker, "dragend", function(){  
                                var position = marker.getPosition();  
                                map.setCenter(position);
                                //update the hidden form with the new location
                                $("#location").val(position.lat() + " ," + position.lng());
                                //reverse geocode the latlng to get human readable address
                                var latlng = new google.maps.LatLng(position.lat(), position.lng());
                                  geocoder.geocode({'latLng': latlng}, function(results, status) {
                                    if (status == google.maps.GeocoderStatus.OK) {
                                      if (results[1]) {
                                          alert(results[1].formatted_address);
                                        map.setZoom(11);
                                        marker = new google.maps.Marker({
                                            position: latlng,
                                            map: map
                                        });
                                        infowindow.setContent(results[1].formatted_address);
                                        infowindow.open(map, marker);
                                      } else {
                                        alert('No results found');
                                      }
                                    } else {
                                      alert('Geocoder failed due to: ' + status);
                                    }
                                  });

                        });
                        google.maps.event.addListener(marker, "drag", function(){  
                                circle.setCenter(marker.getPosition());
                        });
                    } else {
                       alert("Geocode failed. Please edit your address (top of the page) and try again.");
                    }
             });
         }
        google.maps.event.addDomListener(window, "load", initialize);


});
</script>

Emil is correct, infowindow is not defined and so further execution is halted.

You need to add the following, taken from https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding

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

after

var geocoder = new google.maps.Geocoder();

you have a small problem here:

infowindow.setContent(results[1].formatted_address);

infowindow is not defined, hence future javascript will fail.

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