我是React JS的新手。我有下面的代碼來使用JAvascript生成地圖。將JavaScript地圖代碼轉換爲React
<title>Untitled Document</title>
</head>
<body>
<div id="map" style="height:800px;"></div>
<script>
function initMap() {
var myLatLng = {lat: 33.847862, lng: -84.363433};
var locations = [
//list of locations
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
// Create a map object and specify the DOM element for display.
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: true,
zoom: 10
});
var icon = "img/store_marker.png"
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: icon
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("<h3>"+locations[i][0]+ "</h3><br/>"+locations[i][4]+", <br/>"+locations[i][5]+", <br/>"+locations[i][6]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBZqPocCNt5mdLvKi5fm72jq6e9on_IoaM&callback=initMap" async defer></script>
</body>
</html>
我需要使用此代碼來使用React JS生成地圖。我寫了下面的代碼,但是我沒有看到屏幕上顯示的內容。以下是我的App.jsx。
import React from 'react';
import GoogleMap from 'google-map-react';
import MyGreatPlace from './my_great_place.jsx';
class App extends React.Component {
constructor(props) {
super(props);
}
initMap() {
var myLatLng = {lat: 33.847862, lng: -84.363433};
var locations = [
//list of locations
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
// Create a map object and specify the DOM element for display.
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: true,
zoom: 10
});
var icon = "img/store_marker.png"
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: icon
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("<h3>"+locations[i][0]+ "</h3><br/>"+locations[i][4]+", <br/>"+locations[i][5]+", <br/>"+locations[i][6]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
render() {
initMap();
return (
<div id="map" style="height:800px;"></div>
);
}
}
App.propTypes = {
}
App.defaultProps = {
center: [33.847862, -84.363433],
zoom: 10,
scrollwheel: true
}
export default App;
下面是我的index.html。
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBZqPocCNt5mdLvKi5fm72jq6e9on_IoaM" async defer></script>
</body>
</html>
我去掉了「&回調= initMap」,這是那裏的JS HTML鏈接,因爲沒有這樣的回電中作出反應JS。有人可以幫助嗎?
是的,我正在使用babel編譯它。 – mayooran