Using google maps API, how can we set the current location as the default set location using map.setCenter function?

get current location google maps javascript
google maps api current location marker
how to get geolocation in google maps
show marker on google map using address
google maps javascript api
get user location javascript
angular google maps get current location
google maps live tracking api javascript

I am writing JavaScript code using Google Maps API.

map = new google.maps.Map2(document.getElementById("map_canvas"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);

The above code sets the default location of the map canvas to Palo Alto.

How can we write the script in such a way that the setCenter function automatically points to the current location of the client?

You can use the HTML5 GeoLocation API in browsers that support it.

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(success, error);
} else {
  alert('geolocation not supported');
}

function success(position) {
  alert(position.coords.latitude + ', ' + position.coords.longitude);
}

function error(msg) {
  alert('error: ' + msg);
}

Geolocation | Maps JavaScript API, This example creates a map that displays the geographic location of a user or device on a The user must consent to location sharing or else an error is shown. function initMap(): void { setCenter(pos); }, "Error: Your browser doesn't support geolocation. Note: Read the guide on using TypeScript and Google Maps. It originally sets the center to myLatlng1, and the code at the bottom to set it to the user's current location doesn't do anything, any ideas? Thanks in advance. javascript google-maps geolocation

I can think of two possible options.

First you may want to consider using the GeoLocation API as ceejayoz suggested. This is very easy to implement, and it is a fully client-side solution. To center the map using GeoLocation, simply use:

map.setCenter(new google.maps.LatLng(position.coords.latitude, 
                                     position.coords.longitude), 13);

... inside the success() callback of the GeoLocation's getCurrentPosition() method.

Unfortunately only a few modern browsers are currently supporting the GeoLocation API. Therefore you can also consider using a server-side solution to resolve the IP address of the client into the user's location, using a service such as MaxMind's GeoLite City. Then you can simply geocode the city and country of the user inside the browser, using the Google Maps API. The following could be a brief example:

<!DOCTYPE html>
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps API Geocoding Demo</title> 
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false"
            type="text/javascript"></script> 
  </head> 
  <body onunload="GUnload()"> 

    <div id="map_canvas" style="width: 400px; height: 300px"></div> 

    <script type="text/javascript"> 

    var userLocation = 'London, UK';

    if (GBrowserIsCompatible()) {
       var geocoder = new GClientGeocoder();
       geocoder.getLocations(userLocation, function (locations) {         
          if (locations.Placemark) {
             var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
             var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
             var east  = locations.Placemark[0].ExtendedData.LatLonBox.east;
             var west  = locations.Placemark[0].ExtendedData.LatLonBox.west;

             var bounds = new GLatLngBounds(new GLatLng(south, west), 
                                            new GLatLng(north, east));

             var map = new GMap2(document.getElementById("map_canvas"));

             map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
             map.addOverlay(new GMarker(bounds.getCenter()));
          }
       });
    }
    </script> 
  </body> 
</html>

Simply replace userLocation = 'London, UK' with the server-side resolved address. The following is a screenshot from the above example:

You can remove the marker by getting rid of the map.addOverlay(new GMarker(bounds.getCenter())); line.

Controls | Maps JavaScript API, View example. Below is a list of the full set of controls you can use in your maps: This control appears by default in the bottom right corner of the map. The Map� Showing client side Google Map using Javascript is a simple task. In this tutorial, we are going to see how to get current location of the user. In this example, I used Google Map Javascript API to display map and get current location of the user. I have created Google API key which is used to access the Google Map Javascript API to request.

that already exists in the google api:

if (GBrowserIsCompatible()) 
{   
    var map = new google.maps.Map2(document.getElementById("mapdiv"));

    if (google.loader.ClientLocation) 
    {        
        var center = new google.maps.LatLng(
            google.loader.ClientLocation.latitude,
            google.loader.ClientLocation.longitude
        );
        var zoom = 8;

        map.setCenter(center, zoom);
    }
}

There are several threads with the same question...

Google Maps API - Core Objects, Here's the simple example of how to use Google Maps on your web page: be the location that the map is set to. map.setCenter(new GLatLng(37.752927 The second line sets up the default set of user controls, such as panning and zoom controls. We'll We'll put this initialization code into a separate function initialize (): Geolocation is one of the best new HTML5 APIs, so let’s see what we can do with it. In a nutshell, Geolocation allows you to give your current location information to the browser. Google use Geolocation a lot, especially for things like Google Maps, you’re bound to have seen the popups ‘This page would like to use your current location’.

This solution tries to get user location from browser first, if the user refused or any other error occurs it then gets the location from user's IP address

mapUserLocation = () => {
  navigator.geolocation
    ? navigator.geolocation.getCurrentPosition(
        handlePosition,
        getLocationFromIP
      )
    : getLocationFromIP();
};

getLocationFromIP = () => {
  fetch("http://ip-api.com/json")
    .then(response => response.json())
    .then(data => {
      data.lat &&
        data.lon &&
        updateUserPosition({
          lat: data.lat,
          lng: data.lon
        });
    })
    .catch(error => {
      console.log(`Request failed: `, error);
    });
};

handlePosition = position => {
  const userPos = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  };
  updateUserPosition(userPos);
};

updateUserPosition = position => {
  map.setCenter(position, 13);
};

and call it like:

mapUserLocation();

Map at a specified location - Maps API for JavaScript, setCenter() method and map.setZoom() method are able to control the location of the map. JavaScript; HTML. Getting Google Maps JavaScript API Key. Before we start, we first need to get an API key for Google Maps. You can get it from here. The Google Maps API is not entirely free, but it comes with a free plan that is enough for most cases. Got the API keys? Take the third exit from the roundabout and continue with the tutorial. 😉

An updated version of @ceejayoz's answer:

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    } else {
        alert('geolocation not supported');
    }
    function error(msg) {
        alert('error: ' + msg);
    }
    function success(position) {

        var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        var mapOptions = {
            zoom: 12,
            center: myLatlng,
            scaleControl: false,
            draggable: false,
            scrollwheel: false,
            navigationControl: false,
            mapTypeControl: false
        }


        map = new google.maps.Map(document.getElementsByClassName('map-canvas')[0], mapOptions);
        marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'Main map',
            icon: iconBase + 'arrow.png'
        });
    }

Google Map, a location. This field type uses the Google Maps JS API to provide. and an interactive marker. New The Google Map field saves more location data in version 5.8.6! of the map. Height Sets the height of the map. The following code provides helper functionality to use in your project. setCenter( bounds. getCenter() )� This tutorial shows you how to display the geographic location of a user or device on a Google map, using your browser's HTML5 Geolocation feature along with the Maps JavaScript API. (Note that the geographic location of a user will only display if he or she has allowed location sharing.)

Google Maps Events, We still use the map from the previous page: a map centered on London, England. That method takes an object, an event to listen for, and a function to call when the specified event occurs. Set Markers and Open InfoWindow for Each Marker Marker({ position: location, map: map }); var infowindow = new google.maps. To search for places around you and get directions more quickly, center the map on your current location. Learn how to find your current location in Google Maps. Tip: You can find traffic info, public transit options and local places of interest in just a few seconds. Learn more about nearby places and travel.

Google maps service interface v1, Google maps service interface v1 |This javascript class allows you to search specific places and services around your position using Google maps API. var marker = new google.maps.Marker({. map: map,. position: place.geometry. location,. }); setCenter(pos); }, function () { noGeolocation(true); }); }; /** *Set the zoom� Find local businesses, view maps and get driving directions in Google Maps. When you have eliminated the JavaScript , whatever remains must be an empty page. Enable JavaScript to see Google Maps.

Build a Nearby Business Search service with Google Maps Platform, Learn to use Google Maps Platform's Maps and Places APIs to build a local business Google Maps Platform brings the wealth of Google's location-based information to your app. In this lab, you're going to build a webpage that displays a Google map centered Change into the directory you just cloned or downloaded:. Converting a URL that you receive from user input is sometimes tricky. For example, a user may enter an address as "5th&Main St." Generally, you should construct your URL from its parts, treating any user input as literal characters.

Comments
  • The GeoLocation API is the obvious answer. However, even if the API is available, it may take some time on the browser side to get a location fix. Meanwhile you have to show the user some temporary location and then move the map once the location is fixed. This sounds like a GUI challenge to make it feel right. I like Daniel Vassallo's solution if an approximate location is acceptable. Moving the map after it is loaded feels questionable to me.
  • @npdoty possible HTML5 the brand not the spec is relevant here.
  • Note that map.setCenter will no longer accept a zoom level. If you want to change the zoom level too, use map.setZoom.
  • Thanks for the explanation. It never occurred to me that the client side component that are commonly used (pre HTML5) do not have fully integrated geolocation support.
  • The above code loads the map with the location set as palo alto. My actual question was, how can we set the location automatically to the current location of the client.
  • Oh I see ... for that you would need geolocation features ... start reading this: mozilla.com/en/firefox/geolocation