简体   繁体   中英

Limit the number Of Decimal Points Returned on Longitude and Latitude in Google API Map

I have the following code in my script. I would like to limit the number to about 6 digits past the decimal returned on the pin marker. Currently I get about 15 digits past the decimal.

var infowindow = new google.maps.InfoWindow({
   content: + location.lat() + ',' + location.lng()
   // ...
});

If you want to always have six digits after the decimal, even if they are zeroes, you could do:

var infowindow = new google.maps.InfoWindow({
    content:
        location.lat().toFixed(6) +
        ',' +
        location.lng().toFixed(6)
});

Or if you want to remove trailing zeros and also remove the decimal point if the value is a whole number, you could do this:

function formatDecimal( number, precision ) {
    return number.toFixed( precision ).replace( /[\.]?0+$/, '' );
}

var infowindow = new google.maps.InfoWindow({
    content:
        formatDecimal( location.lat(), 6 ) +
        ',' +
        formatDecimal( location.lng(), 6 )
});

BTW, this is a JavaScript question, not a Google Maps API question. location.lat() and location.lng() are JavaScript numbers, so you use JavaScript code to format them as you like. (I'm mentioning this only because it will help you find answers to your coding questions faster.)

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