How to get latitude longitude from google map URL in javascript - javascript

Is there any way by which I can find out the latitude and longitude from the google url using javacript?
I am developing a mobile application in android using phonegap.
HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Map</title>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng( 51.520838, -0.140261 );
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map( document.getElementById( "map_canvas" ), myOptions );
}
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style>
html {
height: 100%;
overflow: hidden;
}
body {
margin: 0;
padding: 0;
height: 100%;
}
#map_canvas {
height: 100%;
}
</style>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Here latitude and longitude needs to be passed to the function in order to load the map. But I do not have it saved in my database for the app instead I have google map url. How can I get long,latitude from a google map url?

Get current Latitude and Longitude
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position) {
var current_lat = position.coords.latitude;
var current_lng = position.coords.longitude;
}
function onError(error)
{
alert(error)
}

Related

How to specify location in google map?

I want to specify location in google map, I have javascript codes work fine but I do know how I can specify location from php variable
Below are sample codes.
<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqgya6hvq6zu3Z2xeT5xEGPPi5pY2ize4&callback=initMap"></script>
</head>
<body>
<?php
//I want to search this location in google map
$location="Kigali Rwanda";
?>
<script>
var myMap;
var myLatlng = new google.maps.LatLng(52.518903284520796,-1.450427753967233);
function initialize() {
var mapOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP ,
scrollwheel: false
}
myMap = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: myMap,
title: 'Name Of Business',
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map" style="width:500px; height: 500px;">
</div>
</body>
</html>
Please anyone can help me
You can use Geocoding service in this case
function initMap() {
//var address = '<?php echo $location ?>';
var address = 'Kigali Rwanda';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
}
#map {
height: 400px;
width: 100%;
}
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
you have to use lat, lng to specifiy location. In case of country or state name you should get lat, lng of the location and define it in the code. insert the value of php variable in hidden input field. On running script get the value and process it.

adding strings in javascript

I am working on creating a page using html and javascript.
I have json file that proves inputs to some of the contents i need.
What Im trying to do is to have address variable setup so that google map API can be displayed on my page.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address = cmpyJson[jobCmpyID].company_name+" Company, "+locJson[jobLocID].location_name;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:200px;"></div>
</body>
</html>
above is part of the code.
the address variable has to look like
var address= "google Company, Austin, TX"
for google to recognize it properly.
if i know for fact that json returns exactly what im asking, what could be the problem here? how could i go about fixing it?
updated to ease some confusions.
when i view the source code on my website, i see that returned values are strings...
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address =Oracle+" Company, "+San Francisco, CA;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:200px;"></div>
</body>
assuming that all of these variables exist, the following line should be:
var address = cmpyJson[jobCmpyID].company_name+" Company, "+locJson[jobLocID].location_name;
I just removed all of the curly brackets to make it syntactically correct.
If address is supposed to produce a string, and pull in parts from the cmpJson object, then do this:
var address =cmpyJson[jobCmpyID].company_name +" Company, "+
locJson[jobLocID].location_name;
You don't need the {{ }} around the JSON object references. Also, if you plan to pass this into google, you need to encode it.

Display the Latitude and Longitude of a searched address on my sites Google-Map using API

I have a section on a website I am developing where the user can input their address into the Google Geocode Api and their homes location is displayed, once the map is displayed the marker cannot be moved neither does the right click bring up the "What's Here" option.
What I am actually trying to get as well as the map view are the co-ordinates for that address ideally with the ability to allow the user to fine tune the marker to lets say the front entrance porch and have the Latitude and Longitude displayed either on the screen or inside of an input field.
Thanks for looking at this for me, I know very little about Javascript programming and greatly appreciate any help that you can offer.
Kind Regards
Ian.
The basic code I've used so far is below:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"> </script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(51.915892, -0.660751);
var mapOptions = {
zoom: 18,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
For that right click function, you'll have to create your own on right clicked location.
google.maps.event.addListener(map, "rightclick", function(event) {
//your code here on right click
});
here is answer to your first query that you want user to fine tune marker by dragging and get lat, lng inside input boxes.
<html>
<head>
<title></title>
<script type='text/javascript' src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(51.915892, -0.660751);
var mapOptions = {
zoom: 18,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: true
});
google.maps.event.addListener(marker,'dragend',function(event) {
document.getElementById('lat').value = event.latLng.lat();
document.getElementById('lng').value = event.latLng.lng();
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#map-canvas {
width: 1000px;
height: 500px;
}
</style><div id="map-canvas"></div>
<input type="text" id="address" placeholder="type your address here"/>
<button onclick="codeAddress()">Show on map</button>
<br>
<br>
<input type="text" id="lat" />
<br>
<input type="text" id="lng" />
</body>
</html>

Running a JavaScript Function From QWebView *Google Maps API, PyQT*

I'm trying to write a piece of code which reads the longitude and latitude from a database and passes that into a JavaScript function which then places a marker in correspondence to the longitude and latitude of the coordinates which have been read from the database.
After the HTML has been set to the QWebView I then use: evaluateJavaScript to attempt to run the function in the JavaScript MarkersFromDatabase.
As you can see I have modified the QWebPage class to display the console error message and when I run the program I get this error:
ReferenceError: Can't find variable: MarkersFromDatabase 0 undefined
I don't understand why it's trying to find a variable when I'm running a function.
I don't understand why this isn't running the function.
Any help would be appreciated. Sorry for the messy JavaScript formatting!
Full Code:
from PyQt4.QtWebKit import *
import sqlite3
from PyQt4.QtSql import *
class CustomQWebPage(QWebPage):
def __init__(self):
super().__init__()
def javaScriptConsoleMessage(self,message,lineNumber,sourceID):
print(message,lineNumber,sourceID)
print("javascript console message^")
class ViewOnlyMap(QWebView):
def __init__(self, parent=None):
super().__init__()
self.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
self.settings().setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
self.settings().setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
self.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
self.CustomPage=CustomQWebPage()
self.Coordinates=None
self.set_code()
self.get_marker_coordinates()
def get_marker_coordinates(self):
with sqlite3.connect("skateboard_progress_tracker.db") as db:
cursor=db.cursor()
sql="select SkateparkLongitude, SkateparkLatitude from Skatepark"
cursor.execute(sql)
self.Coordinates=cursor.fetchall()
for coordinate in self.Coordinates:
self.CustomPage.mainFrame().evaluateJavaScript('MarkersFromDatabase({0},{1})'.format(coordinate[0],coordinate[1]))
print("Marker added")
print(coordinate[0])
print(coordinate[1])
def set_code(self):
self.html='''<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
width: 100%
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
var markers = [];
var results = [];
var coords = [];
var highestLevel;
function initialize() {
var Centre = new google.maps.LatLng(52.20255705185695,0.1373291015625);
var mapOptions = {
zoom: 8,
minZoom: 3,
center: Centre,
}
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
AddMarker(event.latLng);
});
}
function MarkersFromDatabase(SkateparkLat,SkateparkLng) {
var Skatepark = new google.maps.LatLng(SkateparkLat,SkateparkLng);
//return Skatepark;
AddMarker(Skatepark); }
function AddMarker(location) {
var marker = new google.maps.Marker({
title: 'Test',
position: location,
animation: google.maps.Animation.DROP,
map: map
});
//markers.push(marker);
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
markers.push({"Object":marker,"Lat":lat,"Lng":lng});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Skatepark</h1>'+
'<div id="bodyContent">'+
'<p>A skatepark description </p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
google.maps.event.addListener(marker, 'mouseover', function(event) {
infowindow.open(map,marker);
});
}
function GetMarkers(){
return markers;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html> '''
self.setHtml(self.html)
You need to give the web-page a chance to load before attempting to call javascript functions. So add a handler for the loadFinished signal:
class ViewOnlyMap(QWebView):
def __init__(self, parent=None):
super().__init__()
...
self.setPage(self.CustomPage)
self.loadFinished.connect(self.handleLoadFinished)
self.set_code()
def handleLoadFinished(self, ok):
if ok:
print("Page loaded successfully")
self.get_marker_coordinates()
else:
print("Could not load page")

.NET windows app / google map api, cant search the same address twice

a while back someone from stackoverflow helped me come with a nice solution to using google maps api on windows application
html code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize(address) {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Flordia")}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Windows application code
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
WebBrowser1.Document.InvokeScript("initialize", New String() {AddressM.Text})
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Url = New Uri("http://datasharesas.com/CompanyAdmin/map2.html")
End Sub
End Class
image of the project
now the issue is that when i look the same address once, it works perfectly.
when i search it twice i get a grey screen and when i search more than 3 times i get an error script
error message
how can this be fixed ?
thank you in advance,
Leo P.
Geocoding is asynchronous, so in some cases, (depending on how fast it returns), your map is not yet created when you try to use it. You need to create the map first and geocode afterwrds. Try this instead:
script type="text/javascript">
// Global vars
// Sorry, I can't be bothered typing "google.maps." every time. ;-)
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 4,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new G.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

Categories