map.setCenter undefined - google-maps

I'm using GoogleMaps and want to centre it when the orientation changes, but when I call
map.setCenter({...})
I'm receiving an undefined error for setCenter.
Here's my code:
let GoogleMap = {
lat : "",
lng : "",
map : {},
marker : {},
point : {},
init() {
return this
},
create(lat, lng) {
this.lat = lat
this.lng = lng
this.point = {lat: lat,lng: lng};
this.map = new google.maps.Map(document.getElementById('map'), {
center: this.point,
zoom: 17
});
this.marker = new google.maps.Marker({
map: this.map,
position: this.point
});
window.addEventListener('orientationchange', this.doOnOrientationChange);
},
doOnOrientationChange() {
this.map.setCenter({lat: this.lat, lng: this.lng})
}
}
export default GoogleMap
Docs: https://developers.google.com/maps/documentation/javascript/reference#Map
And I grab the google maps api from: https://maps.googleapis.com/maps/api/js?key=KEY&libraries=geometry,places
Any ideas?

Thanks to geocodezip, the issue was scoping, and this wasn't in the correct scope in the orientation event handler.
The fix was to use the bind method
window.addEventListener('orientationchange', this.orientationChange.bind(this));
Full working code:
let GoogleMap = {
lat : "",
lng : "",
map : {},
marker : {},
point : {},
init() {
return this
},
create(lat, lng) {
this.lat = lat
this.lng = lng
this.point = {lat: lat,lng: lng};
this.map = new google.maps.Map(document.getElementById('map'), {
center: this.point,
zoom: 17
});
this.marker = new google.maps.Marker({
map: this.map,
position: this.point
});
window.addEventListener('orientationchange', this.orientationChange.bind(this));
},
orientationChange() {
this.map.setCenter({lat: this.lat, lng: this.lng})
}
}
export default GoogleMap
The map now centres itself as expected when the orientation changes.

Related

getting location TypeError: _this.map.addEventListener is not a function in ionic

Am trying to get the coordinates of location when drag the marker in map. For that i'm using addEventListener and also tried this.map.one() , this.map.on() methods too, to get the latitude and longitude. At the time following same type error are occurred for each.
Error getting location TypeError: _this.map.addEventListener is not a function
Here My code
this.geolocation.getCurrentPosition().then((resp) => {
console.log('latitude',resp.coords.latitude);
console.log('longitude',resp.coords.longitude);
let pos = {
lat: resp.coords.latitude,
lng: resp.coords.longitude
};
this.map = new google.maps.Map(document.getElementById('map'), {
center: { lat: resp.coords.latitude, lng: resp.coords.longitude },
zoom: 15
});
let marker = new google.maps.Marker({
position: pos,
map: this.map,
draggable:true,
title: 'I am here!',
});
console.log(pos);
this.markers.push(marker);
this.map.setCenter(pos);
this.map.addEventListener(GoogleMapsEvent.MARKER_DRAG_END).subscribe(() => {
this.map.getCameraPosition().then((cameraPosition) => {
this.temp = JSON.stringify(cameraPosition.target);
this.temp2 = JSON.parse(this.temp);
this.currentLatitude = this.temp2.lat;
this.currentLongitude = this.temp2.lng;
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(this.currentLatitude, this.currentLongitude);
let request = { latLng: latlng };
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
let address = results[0].formatted_address;
this.locationObject = address;
} else { alert("No address available"); }
}
});
});
});
}).catch((error) => {
console.log('Error getting location', error);
});
I don't know where i did mistake, Please give me some suggestions.
Thanks in Advance
I too had been struggled for 1 week with this phase, finally I tried to call every method separately , and that sounds good. You can try this method.
This is you method for initiat and call map,
this.geolocation.getCurrentPosition().then((response) => {
console.log('latitude',response.coords.latitude);
console.log('longitude',response.coords.longitude);
let position = {
lat: response.coords.latitude,
lng: response.coords.longitude
};
this.map = new google.maps.Map(document.getElementById('map'), {
center: { lat: response.coords.latitude, lng: response.coords.longitude },
zoom: 15
});
this.addMarker();
console.log(position);
}).catch((error) => {
console.log('Error getting location', error);
});
Next call method of marker,
addMarker(){
let marker = new google.maps.Marker(
{
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Whatever you want to display!</h4>";
this.addInfoWindow(marker, content);
}
Next method to catch latitude and longitude
addInfoWindow(marker, content)
{
let infoWindow = new google.maps.InfoWindow(
{
content: content
});
google.maps.event.addListener(marker, 'click', () =>
{
infoWindow.open(this.map, marker);
});
google.maps.event.addListener(marker, 'dragend', function(){
this.markerlatlong = marker.getPosition();
console.log("latitude => "+marker.getPosition().lat());
console.log("longitude => "+marker.getPosition().lng());
});
}

Is there way to get google maps polygon co-ordinates value in string format

This is how I am drawing polygon. And I want it get the polygon area as drawn and mark the properties on the map in next page that lies under the drawn polygon area and also draw the polygon on it.I am getting the co-ordinates of the polygon but it is difficult to send the co-ordinates on the url to next page.
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [ 'polygon']
},
markerOptions: {icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'},
polygonOptions: {
editable: true
}
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
$.each(event.overlay.getPath().getArray(), function(key, latlng){
var lat = latlng.lat();
var lon = latlng.lng();
console.log(lat, lon);
console.log(latlng); //do something with the coordinates
lats.push({lat:lat,lon:lon});
var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
var t = results[0].formatted_address.split(',');
var country = t[t.length-1];
var state = t[t.length-2];
locations.push({'state':state,country:country});
// console.log(locations);
// console.log(lats);
// locations.push({'state:'lat,lon});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
I can suggest using encoded paths in order to send a polygon as a string parameter in the URL of the next page. Maps JavaScript API has geometry library that allows encode and decode array of LatLng into string:
https://developers.google.com/maps/documentation/javascript/reference/3/geometry#encoding
You can use something like
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var encodedPath = google.maps.geometry.encoding.encodePath(event.overlay.getPath());
window.open(m_url + "?path="+encodedPath, "restore polygon");
});
in page with drawing manager and restore array of LatLng on the next page as
let params = (new URL(document.location)).searchParams;
let encodedPath = params.get("path");
if (encodedPath) {
var path = google.maps.geometry.encoding.decodePath(encodedPath);
var polygon = new google.maps.Polygon({
paths: path,
map: map
});
}
Proof of concept
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [ 'polygon']
},
markerOptions: {
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'},
polygonOptions: {
editable: true
},
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var encodedPath = google.maps.geometry.encoding.encodePath(event.overlay.getPath());
console.log(encodedPath);
window.open("http://output.jsbin.com/hicomid?path="+encodedPath, "restore polygon");
});
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=drawing,geometry&callback=initMap"
async defer></script>
You can also check this example on jsfiddle: https://jsfiddle.net/xomena/tpvoL426/
I hope this helps!

SetPosition: not a LatLng or LatLngLiteral: in property lat: not a number using React and Google Maps

I am trying to display multiple markers using google maps and react but keep getting the error mentioned above. The idea is to have multiple markers displayed from lat and long cords in an array. Any thoughts?
Codepen: http://codepen.io/anon/pen/evOoNP?editors=0010
class GMap extends React.Component {
state = { zoom: 10 };
static propTypes() {
initialCenter: React.PropTypes.objectOf(React.PropTypes.number).isRequired
}
render() {
return <div className="GMap">
<div className='UpdatedText'>
<p>Current Zoom: { this.state.zoom }</p>
</div>
<div className='GMap-canvas' ref="mapCanvas">
</div>
</div>
}
componentDidMount() {
// create the map, marker and infoWindow after the component has
// been rendered because we need to manipulate the DOM for Google =(
this.map = this.createMap()
this.marker = this.createMarker()
this.infoWindow = this.createInfoWindow()
// have to define google maps event listeners here too
// because we can't add listeners on the map until its created
google.maps.event.addListener(this.map, 'zoom_changed', ()=> this.handleZoomChange())
}
// clean up event listeners when component unmounts
componentDidUnMount() {
google.maps.event.clearListeners(map, 'zoom_changed')
}
createMap() {
let mapOptions = {
zoom: this.state.zoom,
center: new google.maps.LatLng(38, -78)
}
return new google.maps.Map(this.refs.mapCanvas, mapOptions)
}
mapCenters() {
return new google.maps.LatLng(
this.props.initialCenter.lat,
this.props.initialCenter.lng
)
}
mapCenter() {
const navLinks = [
{location: "Bondi Beach", lat: -33.890542, long: 151.274856},
{location: "Coogee Beach", lat: -33.923036, long: 151.259052},
{location: "Cronulla Beach", lat: -34.028249, long: 151.157507}
];
return navLinks.map((b, i) => {
console.log(b)
return new google.maps.LatLng(b.lat, b.long)
})
}
createMarker() {
return new google.maps.Marker({
position: this.mapCenter(),
map: this.map
})
}
createInfoWindow() {
let contentString = "<div class='InfoWindow'>I'm a Window that contains Info Yay</div>"
return new google.maps.InfoWindow({
map: this.map,
anchor: this.marker,
content: contentString
})
}
handleZoomChange() {
this.setState({
zoom: this.map.getZoom()
})
}
}
var initialCenter = { lng: -90.1056957, lat: 29.9717272 }
ReactDOM.render(<GMap initialCenter={initialCenter} />, document.getElementById('container'));
new google.maps.Marker({
position: this.mapCenter(), // here is the problem
map: this.map
})
Your mapCenter() method returns an array of coordinates, but new google.maps.Marker({}) expects a single LatLng to be passed as position.
You need to update your createMarker() method to create the markers in a loop, for example:
createMarker() {
return this.mapCenter().map( point => {
return new google.maps.Marker({
position: point,
map: this.map
})
});
}
http://codepen.io/anon/pen/yMLYBa?editors=0010

How to Zoom In further in google map to show markers clearly

I have got four markers which will be shown when i zoom in till the last .
The issue i am facing is that the markers one and four are overlapping with each other , and i cannot zoom zoom in further to click on them ?
Is there any solution for this without using Marker cluster??
some part of my code
function addMarker(response, lator, lonor, infowindow) {
if (response.length > 0) {
var global_markers = [];
for (var i = 0; i < response.length; i++) {
var lat = parseFloat(response[i].latitude);
var lng = parseFloat(response[i].longititude);
var dealername = response[i].name;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: "Dealer name: " + dealername,
icon: 'http://maps.google.com/mapfiles/marker.png'
});
global_markers[i] = marker;
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
}
}
}
This is my fiddle
http://jsfiddle.net/3VXTL/13/
Please let me know how to resolve this ??
One option is to make the markers smaller (use the "measle" little red do).
updated fiddle
code snippet:
var response = [{
"longititude": "78.377665",
"latitude": "17.439669",
"name": "one"
}, {
"longititude": "78.377617",
"latitude": "17.439692",
"name": "two"
}, {
"longititude": "78.377644",
"latitude": "17.439674",
"name": "three"
}, {
"longititude": "78.377665",
"latitude": "17.439667",
"name": "four"
}]
initializeCalllater(18.1124372, 79.01929969999999, response);
function initializeCalllater(lator, lonor, response) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lator, lonor);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.trigger(map, 'resize');
map.setCenter(new google.maps.LatLng(lator, lonor));
var infowindow = new google.maps.InfoWindow({});
addMarker(response, lator, lonor, infowindow);
}
function addMarker(response, lator, lonor, infowindow) {
if (response.length > 0) {
var global_markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < response.length; i++) {
var lat = parseFloat(response[i].latitude);
var lng = parseFloat(response[i].longititude);
var dealername = response[i].name;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: "Dealer name: " + dealername,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
bounds.extend(marker.getPosition());
global_markers[i] = marker;
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
}
map.fitBounds(bounds);
}
}
body,
html,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map_canvas" "></div>
If that is not enough, you could change the zIndex of the markers that overlap when you click on one of them (like this question: allow user to move marker position back (z-index?) in google maps custom map).

How do I add a single marker to a Google Map v3?

In the code below, I've been displaying the greyscale of the map using Google Maps v3 with the desired latitude and longitude from the DB. Can someone help me figure out how I can put only one marker at the desired latitude and longitude.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var latitude = <?php echo $store_details->latitude; ?>;
var longitude = <?php echo $store_details->longitude; ?>;
var brooklyn = new google.maps.LatLng(latitude, longitude);
var MY_MAPTYPE_ID = 'Greyscale';
function initialize() {
var graystyle = [{
featureType: "all",
elementType: "all",
stylers: [ { saturation: -100 }, { visibility: "on" } ]
}];
var mapOptions = {
zoom: 15,
center: brooklyn,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID]
},
mapTypeId: MY_MAPTYPE_ID
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var styledMapOptions = {
name: "Greyscale"
};
var grayMapType = new google.maps.StyledMapType(graystyle, styledMapOptions);
map.mapTypes.set(MY_MAPTYPE_ID, grayMapType);
}
</script>
var latlng = new google.maps.LatLng(latitude,longitude);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
Have you tried the docs?
https://developers.google.com/maps/documentation/javascript/overlays#Markers
var marker = new google.maps.Marker({
position: latLng,
map: map
});
this is the syntax
and if you want example click here
I use a function to be able to place as many markers as I want without coding the same lines time after time (markers is a global array):
var markers = createMarker(map, new google.maps.LatLng(50.746853, 5.497167), MyTitle, MyMarkerImage, '#FF0099');
function createMarker(map, pos, titleString, myJPGfile, colorCode) {
var marker = new google.maps.Marker({
map: map,
position: pos,
title: titleString,
icon: myJPGfile,
color: colorCode });
return marker;
}