How set the current position center on the map? - javascript

I tried different approaches which I found on this site and in web but they don't work for me(
This is my code:
<h:panelGroup id="GMWrapper" style="background-color: red">
<p:gmap widgetVar="mainMap" center="49.835, 24.0083" zoom="15"
id="mainGoogleMap" type="HYBRID"
style="width: 600px; height: 400px" model="#{userPlaces.model}"
styleClass="gmappStyle" onPointClick="handlePointClick(event)" />
<p:commandButton onclick="someFunc()"></p:commandButton>
<script type="text/javascript">
function someFunc() {
if (navigator.geolocation) {
alert("Start")
navigator.geolocation
.getCurrentPosition(success);
alert("Successful!")
var elem = document
.getElementById("mainGoogleMap");
alert("Element was find")
elem.setCenter(new google.maps.LatLng(37.4419, -122.1419));
alert("Good done!");
} else {
error('Geo Location is not supported');
currentLat = 0.0;
currentLng = 0.0;
}
}
var currentLat;
var currentLng;
function success(position) {
currentLat = position.coords.latitude;
currentLng = position.coords.longitude;
}
</script>
</h:panelGroup>
Javascript code works to alert("Element was find")
Also I tried:
elem.setAttribute("center", currentLat.toString() + ", " + currentLng.toString());
elem.setAttribute("center", currentLat + ", " + currentLng);
elem.setAttribute("center", "37.4419, -122.1419");
and few other..

From the google maps docs: panTo(latLng:LatLng|LatLngLiteral) - Changes the center of the map to the given LatLng. If the change is less than both the width and height of the map, the transition will be smoothly animated. Below is a snippet that creates a map and centers the map at a location.
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.panTo(new google.maps.LatLng(37.4419, -122.1419));
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

Related

Trying to get dynamic location (latitude & longitude) to use it in Places api

I'm trying to build a small project where we get specific nearby places (schools, hospitals, cafes etc) around 5kms radius on clicking a radio button.Here I'm trying to use the geolocation to get the dynamic location(latitude and longitude) so that I can get user current location where ever this app is used.What happening is, the map is not loading on page load while the first radio button is already checked but it is working fine when I switch to other radio buttons.
I'm not an expert in JavaScript.
Below is my HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Google Maps</title>
<style>
#map {
height: 100%;
width: 100%;
}
#box{
height:500px;
width:80%;
margin-left:10%;
margin-right:10%;
border:2px solid black;
}
h1{
text-align:center;
font-family:sans-serif;
}
form {
text-align: center;
}
</style>
</head>
<body>
<h1>Google Maps</h1>
<form>
<input type="radio" id="school" name="places" value="School" checked onClick="load();">Schools
<input type="radio" id="hospital" name="places" value="Hospital" onClick="load();">Hospitals
<input type="radio" id="cafe" name="places" value="Hotel" onClick="load();">Cafes
<input type="radio" id="atm" name="places" value="atm" onClick="load();">ATM's
</form>
<br>
<div id="box">
<div id="map"></div>
</div>
<script type = "text/javascript" src="maps.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBVOCb1nOuIrbnvnTYIYTKMqs2y5ecuMi8&signed_in=true&libraries=places&callback=load" async defer></script>
</body>
</html>
Here's my JavaScript code
var map;
var infowindow;
var myLat;
var myLong;
x = navigator.geolocation;
x. getCurrentPosition(success);
function success(position){
myLat = position.coords.latitude;
myLong = position.coords.longitude;
}
function load() {
//var hyderabad = {lat: 17.46724, lng: 78.53591};
var hyderabad = new google.maps.LatLng(myLat , myLong);
map = new google.maps.Map(document.getElementById('map'), {
center: hyderabad,
zoom: 12
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
var place;
if (document.getElementById('school').checked) {
place = "school"
}
else if (document.getElementById('hospital').checked) {
place = "hospital"
}
else if (document.getElementById('cafe').checked) {
place = "cafe"
}
else if (document.getElementById('atm').checked) {
place = "atm"
}
service.nearbySearch({
location: hyderabad,
radius: 5000,
type: [place]
}, 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, 'mouseover', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}

zoom_changed listener doesn't work for me

I'm trying to use a zoom listener event in a google maps so that I can resize some axis I have in it. As a beginning, I'm trying to use an alert so that I can see whether if the listener detects a change in the zoom level or not, but I'm not able to get any alert at all. My code is the following:
<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 - pygmaps </title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false"></script>
<script type="text/javascript">
var map;
function initialize() {
var centerlatlng = new google.maps.LatLng(49.801674, 11.188139);
var myOptions = {
zoom: 18,
center: centerlatlng,
scaleControl:true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
* plotting stuff *
google.maps.event.addDomListener(window, 'load',initialize);
google.maps.event.addDomListener(maps,'zoom_changed', function()
{
alert("changed");
});
</script>
</head>
<body>
<div style="text-align:center;">
<button onclick="draw_axis()">Enable/Disable Axis</button> <br><br> <div id="log"></div>
</div>
<div id="map_canvas" style="width: 100%; height: 90%;"></div>
</body>
</html>
Does anyone see the problem?
The map variable isn't defined when you create the zoom_changed listener, it is created later, when the initialize function runs (also the variable is map, not maps).
code snippet:
var map;
function initialize() {
var centerlatlng = new google.maps.LatLng(49.801674, 11.188139);
var myOptions = {
zoom: 18,
center: centerlatlng,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addDomListener(map, 'zoom_changed', function() {
alert("changed");
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div style="text-align:center;">
<div id="log"></div>
</div>
<div id="map_canvas" style="width: 100%; height: 90%;"></div>
You need to set zoom_changed event on the instance of google.maps.Map inside your initialize() function.
map.addListener('zoom_changed', function() {
alert("changed");
});

Drag marker on Google maps and receive its updated position [duplicate]

I have made a Google Version 3 Geocoder , I want to be able to pick up the coordinates of the marker when it is dragged or clicked. Below is my code:
<!DOCTYPE html>
<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>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps/api/js?v=3.5&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
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,
draggable: true,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<style type="text/css">
#controls {
position: absolute;
bottom: 1em;
left: 100px;
width: 400px;
z-index: 20000;
padding: 0 0.5em 0.5em 0.5em;
}
html, body, #map_canvas {
margin: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body onload="initialize()">
<div id="controls">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map_canvas"></div>
</body>
</html>
I have tried to use the following code to do this but it does not seem to work.
// Javascript//
google.maps.event.addListener(marker, 'dragend', function(evt){
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(marker, 'dragstart', function(evt){
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(marker.position);
marker.setMap(map);
//HTML//
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
That code works just fine if you put it in the correct place:
http://www.geocodezip.com/BlakeLoizides_geocode.html
(inside the callback routine, the marker is local to it)

Third party latitude and longitude are not matching in google map

I have an external json which I am trying to overlay on a google map. The overall plumbing works fine.
The map gets generated. Data gets iterated, and markers are placed by reading the coordinates. But the when i look at the map the coordinates are way off on the map. The data set can not be wrong, i can give my word on that. Is there some adjustment I need to make to get this thing map to each other. Here is my code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.748433, -73.985655),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
<script type="text/javascript">
$(document).ready(function() {
var image = 'http://soumghosh.com/otherProjects/doitt/images/marker.png';
$.getJSON("http://data.cityofnewyork.us/resource/jfzu-yy6n.json", function(json1) {
$.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.facility_address.latitude, data.facility_address.longitude);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
title: data.title,
icon:image
});
marker.setMap(map);
});
});
});
</script>
</body>
</html>

Placing a marker in Google maps

So I am preparing a page which has a Google Map and there are two forms namely latitude and longitude , and a submit button.
On entering the longitude and latitude the map is centered to the desired location and puts a marker there.
The problem I am facing is that whenever I put a new lat/long , the old marker won't go.
So basically if entered first lat/long : 10/12 , it would center to that and place a marker there, but when i enter the second lat/long (say) : 11/12 , it would center to that too and place a marker there also while the first one is not removed.
I want the page to be whenever the a new entered in the form only that one reflects in the form no old markers.
Here's my CODE :
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(11.6667,76.2667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function pan() {
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
var marker = new google.maps.Marker({
map: map,
position: panPoint,
});
}
</script>
</head>
<body>
Latitude:<input type="text" id="lat" >
Longitude:<input type="text" id="lng">
<input type="button" value="updateCenter" onclick="pan()" />
<div id="map-canvas"></div>
</body>
</html>
Some help would be useful
You need to clear markers each time in order to do that.
To clean marker keep marker as global variable, eg.
function pan() {
try{
marker.setMap(null);//clear marker
}
catch(err){
}
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
//declare marker as global variable
marker = new google.maps.Marker({
map: map,
position: panPoint,
});
}
That should do the trick.
use this code
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var markersArray=[];
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(11.6667,76.2667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function pan() {
deleteOverlays();
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
var marker = new google.maps.Marker({
map: map,
position: panPoint,
});
markersArray.push(marker);
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body>
Latitude:<input type="text" id="lat" >
Longitude:<input type="text" id="lng">
<input type="button" value="updateCenter" onclick="pan()" />
<div id="map-canvas"></div>
</body>
</html>
In the pan function before adding the new marker, try to remove all the present markers Google Maps API v3: How to remove all markers?

Categories