Search code examples
javascriptcssgoogle-mapscurrentlocation

Search Nearby School at current location using Google maps?


I am trying to show nearby schools at current location but, i dont know how to merge both of them, I made a separate program for getting current location, but now i want to show nearby locations around this current location. I have made a fiddle. Here we are giving static lat and longs i want them to be my current locations lat and longs. So that on my current location i can see nearby schools

var pyrmont = {lat: -33.867, lng: 151.195};

Solution

  • Please try this code.

    And here you need to remove callback from the script tag callback=initMap so it will look like as below.

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places" async defer></script> 
    

    Because first we are calling getLocation() and after getting value from geolocation we are calling initMap(); manually.

    var temp_lat = '';
        var temp_lng = '';
        var map;
        var infowindow;
        getLocation();
        function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else { 
                temp_lat = 0.0; //set default lat value
                temp_lng = 0.0; //set default lng value
        }
    }
    
    function showPosition(position) {
        temp_lat = position.coords.latitude;
        temp_lng = position.coords.longitude;
        initMap();
    }
    
    
     function initMap() 
     {
     var pyrmont = {lat: temp_lat, lng: temp_lng};
     map = new google.maps.Map(document.getElementById('map'),
     { center: pyrmont, zoom: 15 }); 
     infowindow = new google.maps.InfoWindow(); 
     var service = new google.maps.places.PlacesService(map);  service.nearbySearch(
     { location: pyrmont, radius: 500, type: ['school'] },
     callback); } 
     function callback(results, status) { 
     if (status === google.maps.places.PlacesServiceStatus.OK) 
     { 
     for (var i = 0; i < results.length; i++) 
     { createMarker(results[i]); } } } function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(place.name); infowindow.open(map, this); }); }
    

    Hope this helps.